javascript - 猫鼬redis缓存
问题描述
https://medium.com/@haimrait/how-to-add-a-redis-cache-layer-to-mongoose-in-node-js-a9729181ad69
在本指南中。所以我主要做这样的查询
{
id: <guild id>
}
所以每当创建新文档时。
const book = new Book({
title,
content,
author
});
try {
await book.save();
clearKey(Book.collection.collectionName);
res.send(book);
} catch (err) {
res.send(400, err);
}
如果我使用 {id: },它会从缓存中删除东西,还是只会删除缓存中类似于空对象或 Model#find() 的数据?
我还有另一个与此无关但可以问的问题。想象一下我这样做
const result = Model.findOne()
Cache.set(<anything>, JSON.stringify(result));
const cached = Cache.get(<anything>)
const result = new Model(cached);
result.message++;
await result.save().catch(console.error)
它抛出 MongoError: E11000 duplicate key error collection: How to fix that?
解决方案
clearKey(Book.collection.collectionName)
简而言之,它将清除集合的所有缓存。
TLDR
你的情况this.hashKey = JSON.stringify(options.key || this.mongooseCollection.name);
是collectionName
https://redis.io/commands/hget
返回与存储在 key 的哈希中的字段关联的值。
clearKey(hashKey) {
client.del(JSON.stringify(hashKey));
}
删除指定的键。如果键不存在,则忽略它。
因此,当您调用clearKey(Book.collection.collectionName);
它时client.del
,它将删除该特定集合的所有记录。因为完整的哈希被删除。
要删除特定字段而不是完整哈希:-
https://redis.io/commands/HDEL
从存储在 key 的哈希中删除指定的字段。此哈希中不存在的指定字段将被忽略。如果 key 不存在,则将其视为空哈希,此命令返回 0。
推荐阅读
- excel - 将值分配给数组时出现类型不匹配错误
- mysql - 如何使用 NodeJS 在 MySQL 数据库表中插入行
- python - 如何将模块中的所有 printf 样式转换为 python 中的格式化样式?
- powershell - 从 AD 组中删除成员而不使用模块
- ios - 仅一个请求的不同超时间隔
- python - 检测到脚本已运行时如何保存脚本?
- android - 创建 8 位灰度位图
- java - 用于在多个线程上发布 json 消息以进行负载测试的 Java 代码
- r - 有没有办法在比较不同类型时禁用 R 中的自动强制
- python-3.x - 在 Python 上使用 BeautifulSoup 进行网页抓取