TypeORM中文文档 v1.1
Query Builder / 缓存查询
GitHub

缓存查询

Caching queries 英文原文 Markdown

你可以缓存这些 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 清空缓存中存储的所有内容。