缓存查询
你可以缓存这些 QueryBuilder 方法所选取的结果:getMany、getOne、getRawMany、getRawOne 和 getCount。
你也可以缓存 Repository 和 EntityManager 的 find* 与 count* 方法所选取的结果。
要启用缓存,你需要在数据源选项中显式开启它:
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: true
}首次启用缓存时,你必须同步数据库结构(使用 CLI、迁移或 synchronize 数据源选项)。
之后在 QueryBuilder 中你就可以为任意查询启用查询缓存:
const users = await dataSource
.createQueryBuilder(User, "user")
.where("user.isAdmin = :isAdmin", { isAdmin: true })
.cache(true)
.getMany()等价的 Repository 查询:
const users = await dataSource.getRepository(User).find({
where: { isAdmin: true },
cache: true,
})这会执行一条查询来获取所有管理员用户并缓存结果。下次你执行同样的代码时,它会从缓存中获取所有管理员用户。默认缓存有效期等于 1000 ms,即 1 秒。这意味着在 query builder 代码被调用 1 秒之后缓存就会失效。实际中,这意味着如果用户在 3 秒内打开用户页面 150 次,这段时间内只会执行 3 次查询。在 1 秒缓存窗口内插入的任何用户都不会返回给用户。
你可以通过 QueryBuilder 手动修改缓存时间:
const users = await dataSource
.createQueryBuilder(User, "user")
.where("user.isAdmin = :isAdmin", { isAdmin: true })
.cache(60000) // 1 分钟
.getMany()或者通过 Repository:
const users = await dataSource.getRepository(User).find({
where: { isAdmin: true },
cache: 60000,
})或者在数据源选项中全局设置:
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: {
duration: 30000 // 30 秒
}
}此外,你还可以通过 QueryBuilder 设置一个"缓存 id":
const users = await dataSource
.createQueryBuilder(User, "user")
.where("user.isAdmin = :isAdmin", { isAdmin: true })
.cache("users_admins", 25000)
.getMany()或者配合 Repository:
const users = await dataSource.getRepository(User).find({
where: { isAdmin: true },
cache: {
id: "users_admins",
milliseconds: 25000,
},
})这让你能细粒度地控制缓存,例如在插入新用户时清除已缓存的结果:
await dataSource.queryResultCache.remove(["users_admins"])默认情况下,TypeORM 使用一张名为 query-result-cache 的独立表,并把所有查询和结果都存在那里。表名是可配置的,你可以通过在 tableName 属性中指定不同的值来修改它。示例:
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: {
type: "database",
tableName: "configurable-table-query-result-cache"
}
}如果把缓存存在单张数据库表中对你来说不够高效,你可以把缓存类型改成 "redis" 或 "ioredis",TypeORM 会改为把所有缓存记录存在 redis 中。示例:
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: {
type: "redis",
options: {
socket: {
host: "localhost",
port: 6379
}
}
}
}"options" 可以是 node_redis 专属选项,也可以是 ioredis 专属选项,取决于你使用的类型。
如果你想用 IORedis 的集群功能连接 redis-cluster,也可以这样做:
{
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
}
}
}
}
}注意,你仍然可以把 options 作为 IORedis 集群构造函数的第一个参数。
{
...
cache: {
type: "ioredis/cluster",
options: [
{
host: 'localhost',
port: 7000,
},
{
host: 'localhost',
port: 7001,
},
{
host: 'localhost',
port: 7002,
}
]
},
...
}如果内置的缓存提供者都无法满足你的需求,你还可以用 provider 工厂函数指定自己的缓存提供者,该函数需要返回一个实现了 QueryResultCache 接口的新对象:
class CustomQueryResultCache implements QueryResultCache {
constructor(private dataSource: DataSource) {}
...
}{
...
cache: {
provider(dataSource) {
return new CustomQueryResultCache(dataSource);
}
}
}如果你希望忽略缓存错误,并在缓存出错时让查询直接透传到数据库,可以使用 ignoreErrors 选项。示例:
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: {
type: "redis",
options: {
socket: {
host: "localhost",
port: 6379
}
},
ignoreErrors: true
}
}你可以用 typeorm cache:clear 清空缓存中存储的所有内容。
You can cache results selected by these QueryBuilder methods: getMany, getOne, getRawMany, getRawOne and getCount.
You can also cache results selected by find* and count* methods of the Repository and EntityManager.
To enable caching you need to explicitly enable it in data source options:
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: true
}When you enable cache for the first time, you must synchronize your database schema (using CLI, migrations or the synchronize data source option).
Then in QueryBuilder you can enable query cache for any query:
const users = await dataSource
.createQueryBuilder(User, "user")
.where("user.isAdmin = :isAdmin", { isAdmin: true })
.cache(true)
.getMany()Equivalent Repository query:
const users = await dataSource.getRepository(User).find({
where: { isAdmin: true },
cache: true,
})This will execute a query to fetch all admin users and cache the results. Next time you execute the same code, it will get all admin users from the cache. Default cache lifetime is equal to 1000 ms, e.g. 1 second. This means the cache will be invalid 1 second after the query builder code is called. In practice, this means that if users open the user page 150 times within 3 seconds, only three queries will be executed during this period. Any users inserted during the 1 second cache window won't be returned to the user.
You can change cache time manually via QueryBuilder:
const users = await dataSource
.createQueryBuilder(User, "user")
.where("user.isAdmin = :isAdmin", { isAdmin: true })
.cache(60000) // 1 minute
.getMany()Or via Repository:
const users = await dataSource.getRepository(User).find({
where: { isAdmin: true },
cache: 60000,
})Or globally in data source options:
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: {
duration: 30000 // 30 seconds
}
}Also, you can set a "cache id" via QueryBuilder:
const users = await dataSource
.createQueryBuilder(User, "user")
.where("user.isAdmin = :isAdmin", { isAdmin: true })
.cache("users_admins", 25000)
.getMany()Or with Repository:
const users = await dataSource.getRepository(User).find({
where: { isAdmin: true },
cache: {
id: "users_admins",
milliseconds: 25000,
},
})This gives you granular control of your cache, for example, clearing cached results when you insert a new user:
await dataSource.queryResultCache.remove(["users_admins"])By default, TypeORM uses a separate table called query-result-cache and stores all queries and results there. Table name is configurable, so you could change it by specifying a different value in the tableName property. Example:
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: {
type: "database",
tableName: "configurable-table-query-result-cache"
}
}If storing cache in a single database table is not effective for you, you can change the cache type to "redis" or "ioredis" and TypeORM will store all cached records in redis instead. Example:
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: {
type: "redis",
options: {
socket: {
host: "localhost",
port: 6379
}
}
}
}"options" can be node_redis specific options or ioredis specific options depending on what type you're using.
In case you want to connect to a redis-cluster using IORedis's cluster functionality, you can do that as well by doing the following:
{
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
}
}
}
}
}Note that, you can still use options as the first argument of IORedis's cluster constructor.
{
...
cache: {
type: "ioredis/cluster",
options: [
{
host: 'localhost',
port: 7000,
},
{
host: 'localhost',
port: 7001,
},
{
host: 'localhost',
port: 7002,
}
]
},
...
}If none of the built-in cache providers satisfy your demands, then you can also specify your own cache provider by using a provider factory function which needs to return a new object that implements the QueryResultCache interface:
class CustomQueryResultCache implements QueryResultCache {
constructor(private dataSource: DataSource) {}
...
}{
...
cache: {
provider(dataSource) {
return new CustomQueryResultCache(dataSource);
}
}
}If you wish to ignore cache errors and want the queries to pass through to database in case of cache errors, you can use ignoreErrors option. Example:
{
type: "mysql",
host: "localhost",
username: "test",
...
cache: {
type: "redis",
options: {
socket: {
host: "localhost",
port: 6379
}
},
ignoreErrors: true
}
}You can use typeorm cache:clear to clear everything stored in the cache.