# 缓存查询

> 英文标题：Caching queries
> 官网原文：https://typeorm.io/docs/query-builder/caching
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 38 块

---

<!-- EN -->
# Caching queries

<!-- ZH -->
# 缓存查询

<!-- EN -->
You can cache results selected by these `QueryBuilder` methods: `getMany`, `getOne`, `getRawMany`, `getRawOne` and `getCount`.

<!-- ZH -->
你可以缓存这些 `QueryBuilder` 方法所选取的结果：`getMany`、`getOne`、`getRawMany`、`getRawOne` 和 `getCount`。

<!-- EN -->
You can also cache results selected by `find*` and `count*` methods of the `Repository` and `EntityManager`.

<!-- ZH -->
你也可以缓存 `Repository` 和 `EntityManager` 的 `find*` 与 `count*` 方法所选取的结果。

<!-- EN -->
To enable caching you need to explicitly enable it in data source options:

<!-- ZH -->
要启用缓存，你需要在数据源选项中显式开启它：

<!-- EN -->
```typescript
{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: true
}
```

<!-- ZH -->
```typescript
{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: true
}
```

<!-- EN -->
When you enable cache for the first time, you must synchronize your database schema (using CLI, migrations or the `synchronize` data source option).

<!-- ZH -->
首次启用缓存时，你必须同步数据库结构（使用 CLI、迁移或 `synchronize` 数据源选项）。

<!-- EN -->
Then in `QueryBuilder` you can enable query cache for any query:

<!-- ZH -->
之后在 `QueryBuilder` 中你就可以为任意查询启用查询缓存：

<!-- EN -->
```typescript
const users = await dataSource
    .createQueryBuilder(User, "user")
    .where("user.isAdmin = :isAdmin", { isAdmin: true })
    .cache(true)
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .createQueryBuilder(User, "user")
    .where("user.isAdmin = :isAdmin", { isAdmin: true })
    .cache(true)
    .getMany()
```

<!-- EN -->
Equivalent `Repository` query:

<!-- ZH -->
等价的 `Repository` 查询：

<!-- EN -->
```typescript
const users = await dataSource.getRepository(User).find({
    where: { isAdmin: true },
    cache: true,
})
```

<!-- ZH -->
```typescript
const users = await dataSource.getRepository(User).find({
    where: { isAdmin: true },
    cache: true,
})
```

<!-- EN -->
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.

<!-- ZH -->
这会执行一条查询来获取所有管理员用户并缓存结果。下次你执行同样的代码时，它会从缓存中获取所有管理员用户。默认缓存有效期等于 `1000 ms`，即 1 秒。这意味着在 query builder 代码被调用 1 秒之后缓存就会失效。实际中，这意味着如果用户在 3 秒内打开用户页面 150 次，这段时间内只会执行 3 次查询。在 1 秒缓存窗口内插入的任何用户都不会返回给用户。

<!-- EN -->
You can change cache time manually via `QueryBuilder`:

<!-- ZH -->
你可以通过 `QueryBuilder` 手动修改缓存时间：

<!-- EN -->
```typescript
const users = await dataSource
    .createQueryBuilder(User, "user")
    .where("user.isAdmin = :isAdmin", { isAdmin: true })
    .cache(60000) // 1 minute
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .createQueryBuilder(User, "user")
    .where("user.isAdmin = :isAdmin", { isAdmin: true })
    .cache(60000) // 1 分钟
    .getMany()
```

<!-- EN -->
Or via `Repository`:

<!-- ZH -->
或者通过 `Repository`：

<!-- EN -->
```typescript
const users = await dataSource.getRepository(User).find({
    where: { isAdmin: true },
    cache: 60000,
})
```

<!-- ZH -->
```typescript
const users = await dataSource.getRepository(User).find({
    where: { isAdmin: true },
    cache: 60000,
})
```

<!-- EN -->
Or globally in data source options:

<!-- ZH -->
或者在数据源选项中全局设置：

<!-- EN -->
```typescript
{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: {
        duration: 30000 // 30 seconds
    }
}
```

<!-- ZH -->
```typescript
{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: {
        duration: 30000 // 30 秒
    }
}
```

<!-- EN -->
Also, you can set a "cache id" via `QueryBuilder`:

<!-- ZH -->
此外，你还可以通过 `QueryBuilder` 设置一个"缓存 id"：

<!-- EN -->
```typescript
const users = await dataSource
    .createQueryBuilder(User, "user")
    .where("user.isAdmin = :isAdmin", { isAdmin: true })
    .cache("users_admins", 25000)
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .createQueryBuilder(User, "user")
    .where("user.isAdmin = :isAdmin", { isAdmin: true })
    .cache("users_admins", 25000)
    .getMany()
```

<!-- EN -->
Or with `Repository`:

<!-- ZH -->
或者配合 `Repository`：

<!-- EN -->
```typescript
const users = await dataSource.getRepository(User).find({
    where: { isAdmin: true },
    cache: {
        id: "users_admins",
        milliseconds: 25000,
    },
})
```

<!-- ZH -->
```typescript
const users = await dataSource.getRepository(User).find({
    where: { isAdmin: true },
    cache: {
        id: "users_admins",
        milliseconds: 25000,
    },
})
```

<!-- EN -->
This gives you granular control of your cache, for example, clearing cached results when you insert a new user:

<!-- ZH -->
这让你能细粒度地控制缓存，例如在插入新用户时清除已缓存的结果：

<!-- EN -->
```typescript
await dataSource.queryResultCache.remove(["users_admins"])
```

<!-- ZH -->
```typescript
await dataSource.queryResultCache.remove(["users_admins"])
```

<!-- EN -->
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:

<!-- ZH -->
默认情况下，TypeORM 使用一张名为 `query-result-cache` 的独立表，并把所有查询和结果都存在那里。表名是可配置的，你可以通过在 tableName 属性中指定不同的值来修改它。示例：

<!-- EN -->
```typescript
{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: {
        type: "database",
        tableName: "configurable-table-query-result-cache"
    }
}
```

<!-- ZH -->
```typescript
{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: {
        type: "database",
        tableName: "configurable-table-query-result-cache"
    }
}
```

<!-- EN -->
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:

<!-- ZH -->
如果把缓存存在单张数据库表中对你来说不够高效，你可以把缓存类型改成 "redis" 或 "ioredis"，TypeORM 会改为把所有缓存记录存在 redis 中。示例：

<!-- EN -->
```typescript
{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: {
        type: "redis",
        options: {
            socket: {
                host: "localhost",
                port: 6379
            }
        }
    }
}
```

<!-- ZH -->
```typescript
{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: {
        type: "redis",
        options: {
            socket: {
                host: "localhost",
                port: 6379
            }
        }
    }
}
```

<!-- EN -->
"options" can be [node_redis specific options](https://github.com/redis/node-redis/blob/master/docs/client-configuration.md) or [ioredis specific options](https://github.com/luin/ioredis/blob/master/API.md#new-redisport-host-options) depending on what type you're using.

<!-- ZH -->
"options" 可以是 [node_redis 专属选项](https://github.com/redis/node-redis/blob/master/docs/client-configuration.md)，也可以是 [ioredis 专属选项](https://github.com/luin/ioredis/blob/master/API.md#new-redisport-host-options)，取决于你使用的类型。

<!-- EN -->
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:

<!-- ZH -->
如果你想用 IORedis 的集群功能连接 redis-cluster，也可以这样做：

<!-- EN -->
```typescript
{
    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
                }
            }
        }
    }
}
```

<!-- ZH -->
```typescript
{
    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
                }
            }
        }
    }
}
```

<!-- EN -->
Note that, you can still use options as the first argument of IORedis's cluster constructor.

<!-- ZH -->
注意，你仍然可以把 options 作为 IORedis 集群构造函数的第一个参数。

<!-- EN -->
```typescript
{
    ...
    cache: {
        type: "ioredis/cluster",
        options: [
            {
                host: 'localhost',
                port: 7000,
            },
            {
                host: 'localhost',
                port: 7001,
            },
            {
                host: 'localhost',
                port: 7002,
            }
        ]
    },
    ...
}
```

<!-- ZH -->
```typescript
{
    ...
    cache: {
        type: "ioredis/cluster",
        options: [
            {
                host: 'localhost',
                port: 7000,
            },
            {
                host: 'localhost',
                port: 7001,
            },
            {
                host: 'localhost',
                port: 7002,
            }
        ]
    },
    ...
}
```

<!-- EN -->
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:

<!-- ZH -->
如果内置的缓存提供者都无法满足你的需求，你还可以用 `provider` 工厂函数指定自己的缓存提供者，该函数需要返回一个实现了 `QueryResultCache` 接口的新对象：

<!-- EN -->
```typescript
class CustomQueryResultCache implements QueryResultCache {
    constructor(private dataSource: DataSource) {}
    ...
}
```

<!-- ZH -->
```typescript
class CustomQueryResultCache implements QueryResultCache {
    constructor(private dataSource: DataSource) {}
    ...
}
```

<!-- EN -->
```typescript
{
    ...
    cache: {
        provider(dataSource) {
            return new CustomQueryResultCache(dataSource);
        }
    }
}
```

<!-- ZH -->
```typescript
{
    ...
    cache: {
        provider(dataSource) {
            return new CustomQueryResultCache(dataSource);
        }
    }
}
```

<!-- EN -->
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:

<!-- ZH -->
如果你希望忽略缓存错误，并在缓存出错时让查询直接透传到数据库，可以使用 ignoreErrors 选项。示例：

<!-- EN -->
```typescript
{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: {
        type: "redis",
        options: {
            socket: {
                host: "localhost",
                port: 6379
            }
        },
        ignoreErrors: true
    }
}
```

<!-- ZH -->
```typescript
{
    type: "mysql",
    host: "localhost",
    username: "test",
    ...
    cache: {
        type: "redis",
        options: {
            socket: {
                host: "localhost",
                port: 6379
            }
        },
        ignoreErrors: true
    }
}
```

<!-- EN -->
You can use `typeorm cache:clear` to clear everything stored in the cache.

<!-- ZH -->
你可以用 `typeorm cache:clear` 清空缓存中存储的所有内容。
