> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# DNS

> 使用 Bun 的 DNS 模块解析 DNS 记录

Bun 实现了自己的 `dns` 模块和 `node:dns` 模块。

```ts theme={null}
import * as dns from "node:dns";

const addrs = await dns.promises.resolve4("bun.com", { ttl: true });
console.log(addrs);
// => [{ address: "172.67.161.226", ttl: 0 }, ...]
```

```ts theme={null}
import { dns } from "bun";

dns.prefetch("bun.com", 443);
```

***

## Bun 中的 DNS 缓存

Bun 会缓存 DNS 查询结果，使重复连接到同一主机的速度更快。

缓存最多容纳 256 个条目，每个条目最长 30 秒。如果到某主机的连接失败，Bun 会从缓存中移除该主机的条目。到同一主机的并发连接共享同一个 DNS 查询。

此缓存会被以下功能自动使用：

* `bun install`
* `fetch()`
* `node:http`（客户端）
* `Bun.connect`
* `node:net`
* `node:tls`

### 何时应该预取 DNS 条目？

Web 浏览器暴露了 [`<link rel="dns-prefetch">`](https://developer.mozilla.org/en-US/docs/Web/Performance/dns-prefetch)，以便在需要之前解析主机名。在 Bun 中，`dns.prefetch` 做同样的事情：当你已知即将连接到某个主机并希望避免初始 DNS 查询时使用它。

```ts theme={null}
import { dns } from "bun";

dns.prefetch("my.database-host.com", 5432);
```

数据库驱动程序是一个很好的例子：在应用程序启动时预取数据库主机的 DNS 条目，到应用程序其余部分加载完成时，DNS 查询可能已经完成。

### `dns.prefetch`

<Warning>此 API 是实验性的，未来可能会发生变化。</Warning>

`dns.prefetch` 在需要之前解析主机名。

```ts theme={null}
dns.prefetch(hostname: string, port?: number): void;
```

以下是一个示例：

```ts theme={null}
import { dns } from "bun";

dns.prefetch("bun.com", 443);
//
// ... 稍后 ...
await fetch("https://bun.com");
```

### `dns.getCacheStats()`

<Warning>此 API 是实验性的，未来可能会发生变化。</Warning>

`dns.getCacheStats()` 返回当前缓存统计信息，作为一个具有以下属性的对象：

```ts theme={null}
{
  cacheHitsCompleted: number; // 缓存命中完成数
  cacheHitsInflight: number; // 缓存命中进行中
  cacheMisses: number; // 缓存未命中数
  size: number; // DNS 缓存中的条目数
  errors: number; // 连接失败次数
  totalCount: number; // 请求连接的总次数（包括缓存命中和未命中）
}
```

示例：

```ts theme={null}
import { dns } from "bun";

const stats = dns.getCacheStats();
console.log(stats);
// => { cacheHitsCompleted: 0, cacheHitsInflight: 0, cacheMisses: 0, size: 0, errors: 0, totalCount: 0 }
```

### 配置 DNS 缓存 TTL

默认情况下，Bun 缓存 DNS 条目 30 秒。要更改 TTL，设置 `$BUN_CONFIG_DNS_TIME_TO_LIVE_SECONDS` 环境变量。例如，设置为 5 秒：

```sh theme={null}
BUN_CONFIG_DNS_TIME_TO_LIVE_SECONDS=5 bun run my-script.ts
```

#### 为什么默认是 30 秒？

底层的系统 API（`getaddrinfo`）不会暴露 DNS 条目的 TTL，因此 Bun 必须选择一个数字。我们选择 30 秒，因为它足够长，可以体现缓存的好处，且足够短，在 DNS 条目发生变化时不太可能引起问题。[Amazon Web Services 推荐 Java 虚拟机使用 5 秒](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/jvm-ttl-dns.html)，尽管 JVM 的默认配置是无限期缓存。
