Skip to content

Commit 82c7660

Browse files
author
xiongcc
committed
添加第21章:How to set application_name without extra queries
1 parent c62dcb2 commit 82c7660

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# How to set application_name without extra queries
2+
3+
>我每天都会发布一篇新的 PostgreSQL "howto" 文章。加入我的旅程吧 — 订阅、提供反馈、分享!
4+
5+
`application_name` 非常有用,可以控制你和他人在 `pg_stat_activity` 中看到的内容 (该视图中有一个同名的列),以及使用此系统视图的各种工具。此外,当 `log_line_prefix` 包含 `%a` 时,它还会出现在 Postgres 的日志中。
6+
7+
文档:[application_name](https://postgresql.org/docs/current/runtime-config-logging.html#GUC-APPLICATION-NAME)
8+
9+
设置 `application_name` 是一个很好的实践 — 例如,在事件发生期间或之后进行根本原因分析时非常有帮助。
10+
11+
以下方法也可以用于设置其他设置 (包括常规的 Postgres 参数,如 `statement_timeout``work_mem`),但此处我们重点关注 `application_name`
12+
13+
通常,`application_name` 是通过 `SET` 设置的 (抱歉使用了同源词):
14+
15+
```sql
16+
nik=# show application_name;
17+
application_name
18+
------------------
19+
psql
20+
(1 row)
21+
22+
nik=# set application_name = 'human_here';
23+
SET
24+
25+
nik=# select application_name, pid from pg_stat_activity where pid = pg_backend_pid() \gx
26+
-[ RECORD 1 ]----+-----------
27+
application_name | human_here
28+
pid | 93285
29+
```
30+
31+
然而,即使是一个非常快的查询,也意味着额外的RTT ([round-trip time](https://en.wikipedia.org/wiki/Round-trip_delay)),影响延迟,尤其是在与远程服务器进行通信时。
32+
33+
为了避免这种情况,可以使用 `libpq` 的选项。
34+
35+
## 方法1:通过环境变量
36+
37+
```bash
38+
❯ PGAPPNAME=myapp1 psql \
39+
-Xc "show application_name"
40+
application_name
41+
------------------
42+
myapp1
43+
(1 row)
44+
```
45+
46+
(`-X` 表示忽略 `.psqlrc`,这是在自动化脚本中使用 `psql` 时的良好实践。)
47+
48+
## 方法2:通过连接URI
49+
50+
```bash
51+
❯ psql \
52+
"postgresql://?application_name=myapp2" \
53+
-Xc "show application_name"
54+
application_name
55+
------------------
56+
myapp2
57+
(1 row)
58+
```
59+
60+
URI 方法优先于 `PGAPPNAME`
61+
62+
## 在应用程序代码中
63+
64+
所描述的方法不仅可以与 psql 一起使用。以 Node.js 为例:
65+
66+
```bash
67+
❯ node -e "
68+
const { Client } = require('pg');
69+
70+
const client = new Client({
71+
connectionString: 'postgresql://?application_name=mynodeapp'
72+
});
73+
74+
client.connect()
75+
.then(() => client.query('show application_name'))
76+
.then(res => {
77+
console.log(res.rows[0].application_name);
78+
client.end();
79+
});
80+
"
81+
mynodeapp
82+
```

0 commit comments

Comments
 (0)