Opa:如何手动使缓存值失效
设置
我试图实现一个相当常见的缓存模式。这就是我想要发生的事情:
- 第一次请求记录时,它的值被缓存。
- 后续请求将返回缓存的记录。
- 当记录更改时,缓存的版本将被标记为无效。
- 该记录的下一个请求会缓存一个新值。
问题
Cache.simple()
按预期缓存值,但我似乎没有用于使缓存值无效的工具。 Cache.make()
似乎是用于这项工作的工具,但我未能成功使用它。
源
这是一个完整的示例(构建和运行)。我想使 set_name
末尾的缓存记录无效(存储新值后)。如果缓存记录成功失效,则刷新页面时应显示从文本输入提交的名称。
type User.t =
{ id : int
; name : string
}
db /user: intmap(User.t)
create_user() =
match ?/user[0] with
| {none} -> /user[0] <- {id=0 name="tom"}
| _ -> void
set_name(new_name: string) =
/user[0]/name <- new_name
// After setting a new name, invalidate the cached result.
_get_name(uid:int) : string =
/user[uid]/name
get_name = Cache.simple(_get_name)
page() =
do create_user()
<>User's name is "{get_name(0)}"</>
<form onsubmit={_ -> set_name(Dom.get_value(#name_input))}>
<input type="text" id=#name_input />
</form>
server = one_page_server("User", page)
谢谢。
The Setup
I'm trying to implement a fairly common caching pattern. Here's what I want to happen:
- The first time a record is requested, its value is cached.
- Subsequent requests return the cached record.
- When a record is changed, the cached version is marked invalid.
- The next request for the record caches a new value.
The Problem
Cache.simple()
caches values as expected, but I don't seem to have a tool for invalidating a cached value. Cache.make()
seems to be the tool intended for this job, but I've failed to successfully employ it.
The Source
This is a complete example (that builds and runs). I want to invalidate the cached record at the end of set_name
(after storing a new value). If the cached record is successfully invalidated, a name submitted from the text input should be displayed when the page has refreshed.
type User.t =
{ id : int
; name : string
}
db /user: intmap(User.t)
create_user() =
match ?/user[0] with
| {none} -> /user[0] <- {id=0 name="tom"}
| _ -> void
set_name(new_name: string) =
/user[0]/name <- new_name
// After setting a new name, invalidate the cached result.
_get_name(uid:int) : string =
/user[uid]/name
get_name = Cache.simple(_get_name)
page() =
do create_user()
<>User's name is "{get_name(0)}"</>
<form onsubmit={_ -> set_name(Dom.get_value(#name_input))}>
<input type="text" id=#name_input />
</form>
server = one_page_server("User", page)
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实上,如果您想要更多控制,即在这种情况下使结果无效,则
Cache.make
是可行的方法。你遇到了什么问题?您需要首先通过
_get_name
函数创建缓存。为此,您可以模仿Cache.simple
:然后使用
get_name.get
而不是get_name
(get_name
是缓存)并在create_user
函数中使用get_name.invalidate(0)
使缓存结果无效。这有帮助吗?
Indeed
Cache.make
is the way to go if you want more control, i.e. in this case invalidate the results. What problem did you have?You need to start with creating a cache over your
_get_name
function. For that you can mimicCache.simple
:then instead of
get_name
useget_name.get
(get_name
is the cache) and in yourcreate_user
function useget_name.invalidate(0)
to invalidate the cached result.Does that help?