缓存
缓存查询
你可以缓存getMany
,getOne
,getRawMany
,getRawOne
和getCount
这些QueryBuilder
方法的查询结果。
还可以缓存find
,findAndCount
,findByIds
和count
这些Repository
方法查询的结果。
要启用缓存,需要在连接选项中明确启用它:
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: true
}
首次启用缓存时,你必须同步数据库架构(使用synchronize
连接选项
然后在QueryBuilder
中,你可以为任何查询启用查询缓存:
const users = await connection
.createQueryBuilder(User, "user")
.where("user.isAdmin = :isAdmin", { isAdmin: true })
.cache(true)
.getMany();
等同于Repository
查询:
const users = await connection.getRepository(User).find({
where: { isAdmin: true },
cache: true
});
这将执行查询以获取所有1000 ms
,例如
你可以通过QueryBuilder
手动更改缓存时间:
const users = await connection
.createQueryBuilder(User, "user")
.where("user.isAdmin = :isAdmin", { isAdmin: true })
.cache(60000) // 1 分钟
.getMany();
或者通过Repository
const users = await connection.getRepository(User).find({
where: { isAdmin: true },
cache: 60000
});
或者通过全局连接选项:
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: {
duration: 30000 // 30 seconds
}
}
此外,你可以通过QueryBuilder
设置
const users = await connection
.createQueryBuilder(User, "user")
.where("user.isAdmin = :isAdmin", { isAdmin: true })
.cache("users_admins", 25000)
.getMany();
或者通过Repository
const users = await connection.getRepository(User).find({
where: { isAdmin: true },
cache: {
id: "users_admins",
milisseconds: 25000
}
});
这使你可以精确控制缓存,例如,在插入新用户时清除缓存的结果:
await connection.queryResultCache.remove(["users_admins"]);
默认情况下,query-result-cache
的单独表,并在那里存储所有查询和结果表名是可配置的,因此您可以通过在
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: {
type: "database",
tableName: "configurable-table-query-result-cache"
}
}
如果在单个数据库表中存储缓存对你无效,则可以将缓存类型更改为
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: {
type: "redis",
options: {
host: "localhost",
port: 6379
}
}
}
“options” 可以是node_redis specific options 或者 ioredis specific options,具体取决于你使用的类型。
如果你想使用
{
"type": "mysql",
"host": "localhost",
"username": "test",
"cache": {
"type": "ioredis/cluster",
"options": {
"startupNodes": [
{ "host": "localhost", "port": 7000 },
{ "host": "localhost", "port": 7001 },
{ "host": "localhost", "port": 7002 }
],
"options": {
"scaleReads": "all",
"clusterRetryStrategy": function(times) {
return null;
},
"redisOptions": { "maxRetriesPerRequest": 1 }
}
}
}
}
请注意,你仍然可以使用选项作为
{ ...cache: { type: "ioredis/cluster", options: [ { host: 'localhost', port: 7000, }, { host: 'localhost', port: 7001, }, { host: 'localhost', port: 7002, } ] }, ... }