1. 首页 > PostgreSQL教程 > 正文

PostgreSQL教程FG113-PG日常巡检实战教程

本文档详细介绍PostgreSQL数据库日常巡检的方法和流程,包括系统层巡检、数据库层巡检、自动化巡检脚本等,风哥教程参考PostgreSQL官方文档Monitoring内容,适合DBA在生产环境中进行日常运维巡检。

Part01-基础概念与理论知识

1.1 PostgreSQL日常巡检概念

PostgreSQL日常巡检是指定期对数据库系统进行全面检查,发现潜在问题并及时处理的过程。巡检包括系统资源检查、数据库状态检查、性能指标检查、安全检查等多个方面。通过日常巡检,可以及时发现和处理问题,保障数据库稳定运行。更多视频教程www.fgedu.net.cn

PostgreSQL巡检目的:

  • 发现潜在问题,预防故障发生
  • 评估系统性能,优化资源配置
  • 检查安全状态,防范安全风险
  • 记录运行数据,支持容量规划
  • 验证备份有效性,确保数据安全

1.2 PostgreSQL巡检架构

# PostgreSQL巡检架构

# 1. 巡检层次
# 系统层:CPU、内存、磁盘、网络
# 数据库层:连接、事务、锁、缓冲区
# 应用层:查询性能、慢查询
# 安全层:权限、审计、备份

# 2. 巡检流程
┌─────────────┐
│ 开始巡检 │
└──────┬──────┘


┌─────────────┐
│ 系统层检查 │
└──────┬──────┘


┌─────────────┐
│ 数据库层检查│
└──────┬──────┘


┌─────────────┐
│ 性能检查 │
└──────┬──────┘


┌─────────────┐
│ 安全检查 │
└──────┬──────┘


┌─────────────┐
│ 生成报告 │
└──────┬──────┘


┌─────────────┐
│ 问题处理 │
└──────┬──────┘


┌─────────────┐
│ 巡检结束 │
└─────────────┘

# 3. 巡检工具
# 手动巡检:psql命令、系统命令
# 自动巡检:Shell脚本、Python脚本
# 监控系统:Prometheus、Grafana

1.3 PostgreSQL巡检项目

PostgreSQL巡检项目:

  • 系统资源:CPU使用率、内存使用率、磁盘空间、I/O性能
  • 数据库状态:服务状态、连接数、会话状态
  • 复制状态:主从状态、复制延迟、WAL状态
  • 性能指标:TPS/QPS、缓存命中率、查询性能
  • 存储空间:表空间、表大小、索引大小
  • 安全检查:用户权限、审计日志、备份状态
风哥提示:日常巡检是DBA的基本工作,需要建立完善的巡检制度和流程。建议制定标准化的巡检清单,确保每次巡检都覆盖所有重要项目。学习交流加群风哥微信: itpux-com

Part02-生产环境规划与建议

2.1 PostgreSQL巡检规划

# PostgreSQL巡检规划

# 1. 巡检时间规划
# 日常巡检:每天早上9:00
# 周巡检:每周一上午
# 月巡检:每月1号
# 季度巡检:每季度首月1号

# 2. 巡检人员规划
# 日常巡检:值班DBA
# 周巡检:DBA组长
# 月巡检:DBA经理
# 季度巡检:技术总监

# 3. 巡检内容规划
# 日常巡检:系统状态、数据库状态、告警处理
# 周巡检:性能分析、容量分析、问题跟踪
# 月巡检:安全检查、备份验证、优化建议
# 季度巡检:架构评估、容量规划、升级计划

# 4. 巡检报告规划
# 日常巡检:简报(邮件)
# 周巡检:周报(文档)
# 月巡检:月报(PPT)
# 季度巡检:季度报告(正式报告)

# 5. 问题处理规划
# 紧急问题:立即处理
# 重要问题:当天处理
# 一般问题:一周内处理
# 优化建议:纳入计划

2.2 PostgreSQL巡检频率

PostgreSQL巡检频率:

  • 实时监控:连接数、TPS/QPS、错误日志
  • 每小时:复制延迟、锁等待、长事务
  • 每天:磁盘空间、备份状态、表膨胀
  • 每周:索引使用率、查询性能、安全审计
  • 每月:容量规划、性能基线、备份恢复演练

2.3 PostgreSQL巡检报告

# PostgreSQL巡检报告模板

# 1. 报告基本信息
# 报告名称:PostgreSQL数据库巡检报告
# 巡检时间:YYYY-MM-DD HH:MM:SS
# 巡检人员:XXX
# 数据库版本:PostgreSQL 18.0
# 数据库主机:192.168.1.100

# 2. 系统资源状况
# CPU使用率:XX%
# 内存使用率:XX%
# 磁盘使用率:XX%
# I/O性能:XX MB/s

# 3. 数据库状态
# 服务状态:正常/异常
# 连接数:XX / XXX
# 活跃会话:XX
# TPS/QPS:XXX / XXX

# 4. 复制状态
# 主从状态:正常/异常
# 复制延迟:XX MB
# WAL状态:正常/异常

# 5. 性能指标
# 缓存命中率:XX%
# 检查点频率:XX次/小时
# 慢查询数量:XX

# 6. 存储空间
# 表空间使用:XX GB / XX GB
# 表大小TOP10:…
# 索引大小TOP10:…

# 7. 安全检查
# 用户权限:正常/异常
# 审计日志:正常/异常
# 备份状态:正常/异常

# 8. 问题与建议
# 发现问题:…
# 优化建议:…
# 处理计划:…

风哥教程针对风哥教程针对生产环境建议:巡检报告要详细记录巡检结果和发现的问题,便于后续跟踪和处理。建议建立问题跟踪机制,确保问题得到及时解决。学习交流加群风哥QQ113257174

Part03-生产环境项目实施方案

3.1 PostgreSQL系统层巡检实战

3.1.1 CPU和内存检查

# CPU和内存检查

# 1. 检查CPU使用率
$ top -bn1 | head -20

top – 10:00:00 up 30 days, 2:30, 2 users, load average: 0.52, 0.58, 0.59
Tasks: 156 total, 1 running, 155 sleeping, 0 stopped, 0 zombie
%Cpu(s): 5.2 us, 2.1 sy, 0.0 ni, 92.3 id, 0.0 wa, 0.4 hi, 0.0 si
MiB Mem : 65536.0 total, 12345.6 free, 45000.0 used, 8190.4 buff/cache
MiB Swap: 8192.0 total, 8000.0 free, 192.0 used. 20000.0 avail Mem

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
12345 pgsql 20 0 50.0g 45.0g 2.0g S 15.2 70.0 1200:00 postgres
12346 pgsql 20 0 50.0g 45.0g 2.0g S 5.2 70.0 800:00 postgres

# 2. 检查内存使用情况
$ free -h

total used free shared buff/cache available
Mem: 64Gi 45Gi 12Gi 2.0Gi 8.0Gi 20Gi
Swap: 8.0Gi 192Mi 7.8Gi

# 3. 检查大页内存
$ cat /proc/meminfo | grep Huge

HugePages_Total: 16384
HugePages_Free: 12000
HugePages_Rsvd: 0
Hugepagesize: 2048 kB

# 4. 检查NUMA状态
$ numactl –hardware

available: 2 nodes (0-1)
node 0 cpus: 0 1 2 3 4 5 6 7
node 0 size: 32768 MB
node 0 free: 8192 MB
node 1 cpus: 8 9 10 11 12 13 14 15
node 1 size: 32768 MB
node 1 free: 8192 MB
node distances:
node 0 1
0: 10 21
1: 21 10

# 5. 检查进程状态
$ ps -ef | grep postgres | head -10

pgsql 12345 1 0 Apr01 ? 00:20:00 /postgresql/fgapp/bin/postgres -D /postgresql/fgdata
pgsql 12346 12345 0 Apr01 ? 00:15:00 postgres: checkpointer
pgsql 12347 12345 0 Apr01 ? 00:10:00 postgres: background writer
pgsql 12348 12345 0 Apr01 ? 00:05:00 postgres: walwriter
pgsql 12349 12345 0 Apr01 ? 00:08:00 postgres: autovacuum launcher
pgsql 12350 12345 0 Apr01 ? 00:02:00 postgres: stats collector
pgsql 12351 12345 0 Apr01 ? 00:01:00 postgres: logical replication launcher

3.1.2 磁盘和I/O检查

# 磁盘和I/O检查

# 1. 检查磁盘空间
$ df -h

Filesystem Size Used Avail Use% Mounted on
devtmpfs 32G 0 32G 0% /dev
tmpfs 32G 0 32G 0% /dev/shm
tmpfs 32G 2.0G 30G 7% /run
tmpfs 32G 0 32G 0% /sys/fs/cgroup
/dev/sda1 500G 200G 300G 40% /
/dev/sdb1 2T 800G 1.2T 40% /postgresql
/dev/sdc1 1T 500G 500G 50% /postgresql/backup

# 2. 检查数据目录大小
$ du -sh /postgresql/fgdata/*

120G /postgresql/fgdata/base
50G /postgresql/fgdata/global
10G /postgresql/fgdata/pg_wal
5G /postgresql/fgdata/pg_xact

# 3. 检查I/O性能
$ iostat -x 1 5

Linux 5.14.0-284.11.1.el9_2.x86_64 (fgedu.net.cn) 04/07/2026 _x86_64_ (16 CPU)

avg-cpu: %user %nice %system %iowait %steal %idle
5.20 0.00 2.10 0.50 0.00 92.20

Device r/s w/s rMB/s wMB/s rrqm/s wrqm/s %rrqm %wrqm r_await w_await aqu-sz rareq-sz wareq-sz svctm %util
sda 50.00 30.00 2.50 1.50 0.00 5.00 0.00 14.29 1.00 2.00 0.10 51.20 51.20 1.00 8.00
sdb 100.00 80.00 5.00 4.00 0.00 10.00 0.00 11.11 0.50 1.00 0.15 51.20 51.20 0.50 9.00

# 4. 检查磁盘调度算法
$ cat /sys/block/sdb/queue/scheduler

[mq-deadline] none

# 5. 检查文件系统类型
$ mount | grep postgresql

/dev/sdb1 on /postgresql type xfs (rw,noatime,nodiratime,attr2,inode64,logbufs=8,logbsize=256k)

3.2 PostgreSQL数据库层巡检实战

3.2.1 数据库状态检查

# 数据库状态检查

# 1. 检查数据库服务状态
$ pg_isready -h fgedu.localhost -p 5432 -U fgedu -d fgedudb

fgedu.localhost:5432 – accepting connections

# 2. 检查数据库版本
$ psql -U fgedu -d fgedudb -c “SELECT version();”

version
—————————————————————————————————————-
PostgreSQL 18.0 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 11.3.1 20221121 (Red Hat 11.3.1-2), 64-bit
(1 row)

# 3. 检查数据库启动时间
$ psql -U fgedu -d fgedudb -c “SELECT pg_postmaster_start_time();”

pg_postmaster_start_time
——————————-
2026-04-01 10:00:00.123456+08
(1 row)

# 4. 检查数据库列表
$ psql -U fgedu -d fgedudb -c “\l”

List of databases
Name | Owner | Encoding | Collate | Ctype | ICU Locale | Locale Provider | Access privileges
———–+———-+———-+————-+————-+————+—————–+———————–
fgedudb | fgedu | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | libc |
postgres | pgsql | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | libc |
template0 | pgsql | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | libc | =c/pgsql + pgsql=CTc/pgsql
template1 | pgsql | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | libc | =c/pgsql + pgsql=CTc/pgsql
(4 rows)

# 5. 检查数据库大小
$ psql -U fgedu -d fgedudb -c ”
SELECT
datname,
pg_size_pretty(pg_database_size(datname)) as db_size
FROM pg_database
WHERE datistemplate = false
ORDER BY pg_database_size(datname) DESC;

datname | db_size
———-+———
fgedudb | 200 GB
(1 row)

3.2.2 连接和会话检查

# 连接和会话检查

# 1. 检查当前连接数
$ psql -U fgedu -d fgedudb -c ”
SELECT
count(*) as total_connections,
count(*) FILTER (WHERE state = ‘active’) as active,
count(*) FILTER (WHERE state = ‘idle’) as idle,
count(*) FILTER (WHERE state = ‘idle in transaction’) as idle_in_transaction
FROM pg_stat_activity;

total_connections | active | idle | idle_in_transaction
——————-+——–+——+———————
50 | 10 | 35 | 5
(1 row)

# 2. 检查最大连接数配置
$ psql -U fgedu -d fgedudb -c ”
SELECT setting::int as max_connections,
(SELECT count(*) FROM pg_stat_activity) as current_connections,
ROUND((SELECT count(*) FROM pg_stat_activity)::numeric / setting::int * 100, 2) as usage_percent
FROM pg_settings
WHERE name = ‘max_connections’;

max_connections | current_connections | usage_percent
—————–+———————+—————
300 | 50 | 16.67
(1 row)

# 3. 检查长时间运行的查询
$ psql -U fgedu -d fgedudb -c ”
SELECT
pid,
usename,
fgapplication_name,
client_addr,
state,
now() – query_start as duration,
query
FROM pg_stat_activity
WHERE state = ‘active’
AND now() – query_start > interval ‘5 minutes’
ORDER BY duration DESC;

pid | usename | fgapplication_name | client_addr | state | duration | query
——+———+——————+—————+——–+—————–+———————————-
8765 | fgapp_usr | fgedu_fgapp | 192.168.1.50 | active | 00:10:30.123456 | SELECT * FROM fgedu_orders WHERE…
(1 row)

# 4. 检查空闲事务
$ psql -U fgedu -d fgedudb -c ”
SELECT
pid,
usename,
fgapplication_name,
client_addr,
now() – state_change as idle_duration,
query
FROM pg_stat_activity
WHERE state = ‘idle in transaction’
AND now() – state_change > interval ‘5 minutes’
ORDER BY idle_duration DESC;

pid | usename | fgapplication_name | client_addr | idle_duration | query
——+———+——————+—————+—————-+—————————
9876 | fgapp_usr | fgedu_fgapp | 192.168.1.51 | 00:15:00.12345 | UPDATE fgedu_orders SET…
(1 row)

# 5. 检查锁等待
$ psql -U fgedu -d fgedudb -c ”
SELECT
blocked.pid as blocked_pid,
blocked.query as blocked_query,
blocking.pid as blocking_pid,
blocking.query as blocking_query,
blocked.mode as blocked_mode
FROM pg_locks blocked
JOIN pg_stat_activity blocked_act ON blocked.pid = blocked_act.pid
JOIN pg_locks blocking ON blocked.locktype = blocking.locktype
AND blocked.database IS NOT DISTINCT FROM blocking.database
AND blocked.relation IS NOT DISTINCT FROM blocking.relation
AND blocked.page IS NOT DISTINCT FROM blocking.page
AND blocked.tuple IS NOT DISTINCT FROM blocking.tuple
AND blocked.pid != blocking.pid
JOIN pg_stat_activity blocking ON blocking.pid = blocking.pid
WHERE NOT blocked.granted;

blocked_pid | blocked_query | blocking_pid | blocking_query | blocked_mode
————-+——————————————+————–+—————————————+————–
12345 | UPDATE fgedu_orders SET status = ‘…’ | 12346 | UPDATE fgedu_orders SET status = ‘…’ | RowExclusive
(1 row)

3.3 PostgreSQL自动化巡检实战

#!/bin/bash
# pg_daily_inspection.sh
# from:www.itpux.com.qq113257174.wx:itpux-com
# web: http://www.fgedu.net.cn

# PostgreSQL日常巡检脚本

PGHOME=/postgresql/fgapp
PGHOST=fgedu.localhost
PGPORT=5432
PGUSER=fgedu
PGDATABASE=fgedudb
REPORT_DIR=/postgresql/scripts/reports
DATE=$(date +%Y%m%d)
REPORT_FILE=${REPORT_DIR}/inspection_${DATE}.log

mkdir -p ${REPORT_DIR}

log_message() {
echo “[$(date ‘+%Y-%m-%d %H:%M:%S’)] $1” | tee -a ${REPORT_FILE}
}

log_message “==========================================”
log_message “PostgreSQL数据库日常巡检报告”
log_message “巡检时间: $(date)”
log_message “数据库主机: $(hostname)”
log_message “==========================================”

# 1. 系统资源检查
log_message “”
log_message “=== 系统资源检查 ===”

# CPU使用率
CPU_USAGE=$(top -bn1 | grep “Cpu(s)” | awk ‘{print $2}’ | cut -d’%’ -f1)
log_message “CPU使用率: ${CPU_USAGE}%”

# 内存使用率
MEM_USAGE=$(free | grep Mem | awk ‘{printf “%.2f”, $3/$2 * 100}’)
log_message “内存使用率: ${MEM_USAGE}%”

# 磁盘使用率
log_message “磁盘使用情况:”
df -h | grep -E “^/dev|Filesystem” | tee -a ${REPORT_FILE}

# 2. 数据库状态检查
log_message “”
log_message “=== 数据库状态检查 ===”

# 数据库服务状态
DB_STATUS=$(${PGHOME}/bin/pg_isready -h ${PGHOST} -p ${PGPORT} -U ${PGUSER} -d ${PGDATABASE} 2>&1)
log_message “数据库服务状态: ${DB_STATUS}”

# 数据库版本
DB_VERSION=$(${PGHOME}/bin/psql -h ${PGHOST} -p ${PGPORT} -U ${PGUSER} -d ${PGDATABASE} -t -c “SELECT version();” 2>/dev/null | head -1)
log_message “数据库版本: ${DB_VERSION}”

# 3. 连接数检查
log_message “”
log_message “=== 连接数检查 ===”

CONN_INFO=$(${PGHOME}/bin/psql -h ${PGHOST} -p ${PGPORT} -U ${PGUSER} -d ${PGDATABASE} -t -c ”
SELECT ‘当前连接: ‘ || count(*) || ‘, 最大连接: ‘ || setting ||
‘, 使用率: ‘ || ROUND(count(*)::numeric / setting::numeric * 100, 2) || ‘%’
FROM pg_stat_activity, pg_settings
WHERE name = ‘max_connections’;
” 2>/dev/null)
log_message “${CONN_INFO}”

# 4. 复制状态检查
log_message “”
log_message “=== 复制状态检查 ===”

IS_PRIMARY=$(${PGHOME}/bin/psql -h ${PGHOST} -p ${PGPORT} -U ${PGUSER} -d ${PGDATABASE} -t -c “SELECT NOT pg_is_in_recovery();” 2>/dev/null | tr -d ‘ ‘)

if [ “${IS_PRIMARY}” = “t” ]; then
log_message “角色: 主库”

REPL_INFO=$(${PGHOME}/bin/psql -h ${PGHOST} -p ${PGPORT} -U ${PGUSER} -d ${PGDATABASE} -t -c ”
SELECT ‘备库数量: ‘ || count(*) || ‘, 最大延迟: ‘ || COALESCE(max(pg_wal_lsn_diff(sent_lsn, replay_lsn)), 0) || ‘ bytes’
FROM pg_stat_replication;
” 2>/dev/null)
log_message “${REPL_INFO}”
else
log_message “角色: 备库”

REPL_LAG=$(${PGHOME}/bin/psql -h ${PGHOST} -p ${PGPORT} -U ${PGUSER} -d ${PGDATABASE} -t -c ”
SELECT pg_wal_lsn_diff(pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn());
” 2>/dev/null | tr -d ‘ ‘)
log_message “复制延迟: ${REPL_LAG} bytes”
fi

# 5. 表空间检查
log_message “”
log_message “=== 表空间检查 ===”

${PGHOME}/bin/psql -h ${PGHOST} -p ${PGPORT} -U ${PGUSER} -d ${PGDATABASE} -c ”
SELECT
spcname as tablespace,
pg_size_pretty(pg_tablespace_size(oid)) as size
FROM pg_tablespace
ORDER BY pg_tablespace_size(oid) DESC;
” 2>/dev/null | tee -a ${REPORT_FILE}

# 6. 表大小检查
log_message “”
log_message “=== 表大小TOP10 ===”

${PGHOME}/bin/psql -h ${PGHOST} -p ${PGPORT} -U ${PGUSER} -d ${PGDATABASE} -c ”
SELECT
schemaname || ‘.’ || relname as table_name,
pg_size_pretty(pg_total_relation_size(schemaname || ‘.’ || relname)) as total_size,
n_live_tup as live_tuples,
n_dead_tup as dead_tuples
FROM pg_stat_user_tables
ORDER BY pg_total_relation_size(schemaname || ‘.’ || relname) DESC
LIMIT 10;
” 2>/dev/null | tee -a ${REPORT_FILE}

# 7. 索引检查
log_message “”
log_message “=== 未使用索引检查 ===”

${PGHOME}/bin/psql -h ${PGHOST} -p ${PGPORT} -U ${PGUSER} -d ${PGDATABASE} -c ”
SELECT
schemaname || ‘.’ || relname as table_name,
indexrelname as index_name,
pg_size_pretty(pg_relation_size(indexrelid)) as index_size,
idx_scan as index_scans
FROM pg_stat_user_indexes
WHERE idx_scan = 0
AND indexrelname NOT LIKE ‘%_pkey’
ORDER BY pg_relation_size(indexrelid) DESC
LIMIT 10;
” 2>/dev/null | tee -a ${REPORT_FILE}

log_message “”
log_message “==========================================”
log_message “巡检完成”
log_message “报告文件: ${REPORT_FILE}”
log_message “==========================================”

风哥提示:自动化巡检脚本可以大大提高巡检效率,建议根据实际需求定制巡检内容。巡检结果要保存历史记录,便于后续分析和对比。更多学习教程公众号风哥教程itpux_com

Part04-生产案例与实战讲解

4.1 PostgreSQL日常巡检案例

# PostgreSQL日常巡检案例

# 场景:每日例行巡检

# 1. 执行巡检脚本
$ /postgresql/scripts/pg_daily_inspection.sh

[2026-04-07 09:00:00] ==========================================
[2026-04-07 09:00:00] PostgreSQL数据库日常巡检报告
[2026-04-07 09:00:00] 巡检时间: 2026-04-07 09:00:00
[2026-04-07 09:00:00] 数据库主机: fgedu.net.cn
[2026-04-07 09:00:00] ==========================================

[2026-04-07 09:00:00] === 系统资源检查 ===
[2026-04-07 09:00:00] CPU使用率: 15.2%
[2026-04-07 09:00:00] 内存使用率: 68.50%
[2026-04-07 09:00:00] 磁盘使用情况:
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 500G 200G 300G 40% /
/dev/sdb1 2T 800G 1.2T 40% /postgresql

[2026-04-07 09:00:01] === 数据库状态检查 ===
[2026-04-07 09:00:01] 数据库服务状态: fgedu.localhost:5432 – accepting connections
[2026-04-07 09:00:01] 数据库版本: PostgreSQL 18.0 on x86_64-pc-linux-gnu

[2026-04-07 09:00:01] === 连接数检查 ===
[2026-04-07 09:00:01] 当前连接: 50, 最大连接: 300, 使用率: 16.67%

[2026-04-07 09:00:01] === 复制状态检查 ===
[2026-04-07 09:00:01] 角色: 主库
[2026-04-07 09:00:01] 备库数量: 2, 最大延迟: 0 bytes

[2026-04-07 09:00:02] === 表空间检查 ===
tablespace | size
——————+———
pg_default | 150 GB
pg_global | 500 MB
fgedutbs | 50 GB
(3 rows)

[2026-04-07 09:00:03] === 表大小TOP10 ===
table_name | total_size | live_tuples | dead_tuples
—————————+————+————-+————-
public.fgedu_orders | 50 GB | 50000000 | 100000
public.fgedu_customers | 20 GB | 20000000 | 50000
public.fgedu_products | 10 GB | 10000000 | 20000
(3 rows)

[2026-04-07 09:00:04] === 未使用索引检查 ===
table_name | index_name | index_size | index_scans
————————+——————-+————+————-
public.fgedu_logs | idx_logs_temp | 500 MB | 0
(1 row)

[2026-04-07 09:00:05] ==========================================
[2026-04-07 09:00:05] 巡检完成
[2026-04-07 09:00:05] 报告文件: /postgresql/scripts/reports/inspection_20260407.log
[2026-04-07 09:00:05] ==========================================

# 2. 分析巡检结果
# – CPU使用率正常
# – 内存使用率正常
# – 磁盘空间充足
# – 数据库状态正常
# – 连接数正常
# – 复制状态正常
# – 发现未使用索引,需要评估是否删除

# 3. 处理发现的问题
# 删除未使用索引
$ psql -U fgedu -d fgedudb -c “DROP INDEX public.idx_logs_temp;”
DROP INDEX

# 4. 记录处理结果
$ echo “[$(date)] 删除未使用索引 idx_logs_temp” >> /postgresql/scripts/logs/inspection_actions.log

4.2 PostgreSQL健康检查案例

# PostgreSQL健康检查案例

# 场景:数据库健康检查

# 1. 检查数据库配置
$ psql -U fgedu -d fgedudb -c ”
SELECT name, setting, unit, short_desc
FROM pg_settings
WHERE name IN (
‘max_connections’, ‘shared_buffers’, ‘work_mem’,
‘maintenance_work_mem’, ‘effective_cache_size’,
‘checkpoint_timeout’, ‘max_wal_size’, ‘wal_level’
);

name | setting | unit | short_desc
———————+————+——+—————————————————
max_connections | 300 | | Sets the maximum number of concurrent connections.
shared_buffers | 16384 | 8kB | Sets the number of shared memory buffers.
work_mem | 65536 | kB | Sets the maximum memory for query workspaces.
maintenance_work_mem| 1048576 | kB | Sets the maximum memory for maintenance operations.
effective_cache_size| 524288 | 8kB | Sets the planner’s assumption about cache size.
checkpoint_timeout | 300 | s | Sets the maximum time between checkpoints.
max_wal_size | 2048 | MB | Sets the WAL size for checkpoint completion.
wal_level | replica | | Sets the level of information written to the WAL.
(8 rows)

# 2. 检查缓冲区命中率
$ psql -U fgedu -d fgedudb -c ”
SELECT
round(100.0 * buffers_checkpoint / (buffers_checkpoint + buffers_clean + buffers_backend), 2) as checkpoint_write_ratio,
round(100.0 * buffers_alloc / (buffers_checkpoint + buffers_clean + buffers_backend), 2) as alloc_ratio
FROM pg_stat_bgwriter;

checkpoint_write_ratio | alloc_ratio
————————+————-
85.50 | 12.30
(1 row)

# 3. 检查死元组比例
$ psql -U fgedu -d fgedudb -c ”
SELECT
schemaname,
relname,
n_live_tup,
n_dead_tup,
round(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 2) as dead_ratio
FROM pg_stat_user_tables
WHERE n_live_tup + n_dead_tup > 10000
ORDER BY dead_ratio DESC
LIMIT 10;

schemaname | relname | n_live_tup | n_dead_tup | dead_ratio
————+—————-+————+————+————
public | fgedu_logs | 1000000 | 500000 | 33.33
public | fgedu_orders | 50000000 | 100000 | 0.20
public | fgedu_customers| 20000000 | 50000 | 0.25
(3 rows)

# 4. 检查索引膨胀
$ psql -U fgedu -d fgedudb -c ”
SELECT
schemaname || ‘.’ || relname as table_name,
indexrelname as index_name,
pg_size_pretty(pg_relation_size(indexrelid)) as index_size,
idx_scan,
idx_tup_read,
idx_tup_fetch
FROM pg_stat_user_indexes
WHERE idx_scan > 0
ORDER BY pg_relation_size(indexrelid) DESC
LIMIT 10;

table_name | index_name | index_size | idx_scan | idx_tup_read | idx_tup_fetch
————————+———————–+————+———-+————–+—————
public.fgedu_orders | idx_orders_create_time| 5 GB | 1234567 | 12345678 | 12345678
public.fgedu_customers | idx_customers_email | 2 GB | 567890 | 5678901 | 5678901
(2 rows)

# 5. 检查WAL状态
$ psql -U fgedu -d fgedudb -c ”
SELECT
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), ‘0/0’)) as current_wal_position,
count(*) as wal_files
FROM pg_ls_waldir();

current_wal_position | wal_files
———————-+———–
50 GB | 25
(1 row)

4.3 PostgreSQL巡检报告案例

# PostgreSQL巡检报告案例

# 生成HTML格式巡检报告

#!/bin/bash
# pg_inspection_report.sh
# from:www.itpux.com.qq113257174.wx:itpux-com
# web: http://www.fgedu.net.cn

PGHOME=/postgresql/fgapp
REPORT_DIR=/postgresql/scripts/reports
DATE=$(date +%Y%m%d)
HTML_FILE=${REPORT_DIR}/inspection_${DATE}.html

# 生成HTML报告
cat > ${HTML_FILE} << 'EOF'

PostgreSQL数据库巡检报告

巡检时间: DATE_PLACEHOLDER

数据库主机: HOST_PLACEHOLDER

一、系统资源状况

指标 当前值 状态
CPU使用率 CPU_PLACEHOLDER% 正常
内存使用率 MEM_PLACEHOLDER% 正常
磁盘使用率 DISK_PLACEHOLDER% 正常

二、数据库状态

指标 当前值 状态
服务状态 正常 正常
连接数 CONN_PLACEHOLDER 正常
复制状态 REPL_PLACEHOLDER 正常

三、表空间使用情况

TABLESPACE_PLACEHOLDER

四、表大小TOP10

TABLE_PLACEHOLDER

五、问题与建议

  • 建议定期执行VACUUM操作
  • 建议监控长时间运行的查询
  • 建议定期检查索引使用情况

EOF

# 替换占位符
sed -i “s/DATE_PLACEHOLDER/$(date)/g” ${HTML_FILE}
sed -i “s/HOST_PLACEHOLDER/$(hostname)/g” ${HTML_FILE}

echo “巡检报告已生成: ${HTML_FILE}”

风哥教程针对风哥教程针对生产环境建议:巡检报告要定期存档,便于后续分析和对比。建议建立巡检报告库,记录历史巡检数据,支持趋势分析。from PostgreSQL视频:www.itpux.com

Part05-风哥经验总结与分享

5.1 PostgreSQL巡检最佳实践

PostgreSQL巡检最佳实践:

  • 制定巡检计划:明确巡检时间、内容、责任人
  • 标准化巡检流程:使用统一的巡检清单
  • 自动化巡检:使用脚本和工具提高效率
  • 记录巡检结果:保存历史数据便于分析
  • 及时处理问题:发现问题立即处理或跟踪
  • 持续改进:根据实际情况优化巡检内容

5.2 PostgreSQL巡检脚本

# PostgreSQL巡检脚本库

/postgresql/scripts/inspection/
├── pg_daily_inspection.sh # 日常巡检脚本
├── pg_weekly_inspection.sh # 周巡检脚本
├── pg_monthly_inspection.sh # 月巡检脚本
├── pg_health_check.sh # 健康检查脚本
├── pg_inspection_report.sh # 巡检报告生成
└── conf/
└── inspection.conf # 巡检配置文件

5.3 PostgreSQL巡检检查清单

# PostgreSQL巡检检查清单

# 日常巡检(每日)
– [ ] 检查数据库服务状态
– [ ] 检查连接数和会话状态
– [ ] 检查复制状态和延迟
– [ ] 检查磁盘空间使用
– [ ] 检查错误日志
– [ ] 检查备份状态

# 周巡检(每周)
– [ ] 检查表空间使用情况
– [ ] 检查表和索引大小
– [ ] 检查死元组比例
– [ ] 检查索引使用率
– [ ] 检查慢查询日志
– [ ] 检查锁等待情况

# 月巡检(每月)
– [ ] 检查数据库配置
– [ ] 检查用户权限
– [ ] 检查安全审计日志
– [ ] 验证备份恢复
– [ ] 分析性能趋势
– [ ] 容量规划评估

# 季度巡检(每季度)
– [ ] 全面健康检查
– [ ] 性能基线对比
– [ ] 架构评估
– [ ] 升级计划评估
– [ ] 灾备演练
– [ ] 文档更新

风哥提示:日常巡检是保障数据库稳定运行的重要工作,需要认真对待。建议建立完善的巡检制度,确保每次巡检都能发现问题并及时处理。

本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html

联系我们

在线咨询:点击这里给我发消息

微信号:itpux-com

工作日:9:30-18:30,节假日休息