在当今的云计算和企业级环境中,AlmaLinux作为RHEL的社区替代品,其性能表现直接关系到业务的稳定性和成本效益。本文将从系统内核、资源管理、网络栈、存储I/O到应用层,提供一套完整的性能调优策略,并结合实际案例和代码示例,帮助您系统性地提升AlmaLinux服务器的性能。


一、性能优化前的准备工作

在开始任何优化之前,必须建立性能基线,否则无法量化优化效果。

1.1 安装必要的监控工具

# 安装sysstat工具集(包含vmstat, iostat, mpstat等)
sudo dnf install -y sysstat

# 安装性能分析工具
sudo dnf install -y perf htop bpftrace

# 安装网络分析工具
sudo dnf install -y nmon net-tools iperf3

1.2 建立性能基线

# 使用sar收集系统活动数据(每10分钟一次,持续24小时)
sudo sar -o /var/log/sa/sa$(date +%d) 10 144 &

# 使用perf记录系统性能事件
sudo perf record -g -a sleep 30
sudo perf report > /tmp/perf_baseline.txt

# 生成系统资源快照
sudo sysctl -a > /tmp/sysctl_baseline.txt
sudo lscpu > /tmp/cpu_baseline.txt
sudo lsblk > /tmp/disk_baseline.txt

1.3 确定优化目标

  • 吞吐量优化:适用于Web服务器、数据库
  • 延迟优化:适用于实时交易系统、游戏服务器
  • 资源利用率优化:适用于虚拟化环境、容器平台
  • 能效优化:适用于绿色数据中心

二、系统内核级优化

2.1 内核参数调优

2.1.1 CPU调度器优化

AlmaLinux默认使用deadline调度器,对于不同负载需要调整:

# 查看当前调度器
cat /sys/block/sda/queue/scheduler

# 对于I/O密集型应用,使用deadline
echo deadline > /sys/block/sda/queue/scheduler

# 对于数据库应用,使用mq-deadline(多队列)
echo mq-deadline > /sys/block/nvme0n1/queue/scheduler

# 永久化配置
echo 'ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/scheduler}="deadline"' > /etc/udev/rules.d/60-scheduler.rules

2.1.2 内存管理优化

# 优化虚拟内存参数(适用于高内存服务器)
cat > /etc/sysctl.d/99-memory.conf << 'EOF'
# 减少swap使用倾向(适用于内存充足的服务器)
vm.swappiness = 10

# 优化内存回收策略
vm.vfs_cache_pressure = 50

# 增加脏页比例,减少磁盘I/O
vm.dirty_ratio = 15
vm.dirty_background_ratio = 5

# 优化内存分配策略
vm.overcommit_memory = 1
vm.overcommit_ratio = 80
EOF

# 应用配置
sysctl -p /etc/sysctl.d/99-memory.conf

案例分析:某电商平台在促销期间出现内存不足,通过调整vm.swappiness从60降到10,减少了不必要的swap交换,使响应时间从500ms降至150ms。

2.1.3 网络栈优化

# 创建网络优化配置文件
cat > /etc/sysctl.d/99-network.conf << 'EOF'
# TCP缓冲区优化(适用于高带宽网络)
net.core.rmem_max = 134217728
net.core.wmem_max = 134217728
net.ipv4.tcp_rmem = 4096 87380 134217728
net.ipv4.tcp_wmem = 4096 65536 134217728

# TCP连接优化
net.ipv4.tcp_max_syn_backlog = 65536
net.core.somaxconn = 65536
net.ipv4.tcp_max_tw_buckets = 2000000

# TCP拥塞控制算法(根据网络环境选择)
net.ipv4.tcp_congestion_control = bbr

# 端口重用优化
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30

# 连接跟踪优化(适用于防火墙/NAT)
net.netfilter.nf_conntrack_max = 1000000
net.netfilter.nf_conntrack_tcp_timeout_established = 7200
EOF

sysctl -p /etc/sysctl.d/99-network.conf

性能对比测试

# 使用iperf3测试网络吞吐量
# 服务端
iperf3 -s -p 5201

# 客户端(优化前)
iperf3 -c server_ip -p 5201 -t 30

# 客户端(优化后)
iperf3 -c server_ip -p 5201 -t 30 -w 1M

2.2 内核模块优化

2.2.1 I/O调度器模块

# 查看可用调度器模块
lsmod | grep elevator

# 加载多队列I/O调度器(适用于NVMe SSD)
modprobe mq-deadline

# 检查模块参数
modinfo mq-deadline

2.2.2 网络加速模块

# 启用TCP BBR拥塞控制(需要内核4.9+)
modprobe tcp_bbr

# 验证加载
lsmod | grep bbr

# 设置为默认
echo "net.core.default_qdisc=fq" >> /etc/sysctl.d/99-network.conf
echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.d/99-network.conf

三、资源管理与调度优化

3.1 CPU资源优化

3.1.1 CPU亲和性设置

# 查看CPU拓扑
lscpu | grep -E "CPU\(s\)|Core\(s\)|Socket\(s\)"

# 设置进程CPU亲和性(示例:将nginx绑定到CPU 0-3)
# 方法1:使用taskset
taskset -cp 0-3 $(pgrep nginx)

# 方法2:使用systemd服务配置
cat > /etc/systemd/system/nginx.service.d/override.conf << 'EOF'
[Service]
CPUAffinity=0-3
EOF

# 方法3:使用cgroups v2(AlmaLinux 9默认启用)
# 创建cgroup
mkdir -p /sys/fs/cgroup/system.slice/nginx.service
echo "0-3" > /sys/fs/cgroup/system.slice/nginx.service/cpuset.cpus

3.1.2 CPU频率调节

# 安装cpupower工具
sudo dnf install -y cpupower

# 查看当前策略
cpupower frequency-info

# 设置性能模式(适用于数据库服务器)
cpupower frequency-set -g performance

# 设置节能模式(适用于低负载服务器)
cpupower frequency-set -g powersave

# 永久化配置
cat > /etc/sysconfig/cpupower << 'EOF'
GOVERNOR="performance"
EOF

systemctl enable cpupower
systemctl start cpupower

3.2 内存资源优化

3.2.1 Transparent Huge Pages (THP) 调优

# 查看THP状态
cat /sys/kernel/mm/transparent_hugepage/enabled

# 对于数据库应用,建议禁用THP
echo never > /sys/kernel/mm/transparent_hugepage/enabled
echo never > /sys/kernel/mm/transparent_hugepage/defrag

# 永久化配置
cat > /etc/systemd/system/disable-thp.service << 'EOF'
[Unit]
Description=Disable Transparent Huge Pages
DefaultDependencies=no
After=sysinit.target local-fs.target
Before=basic.target

[Service]
Type=oneshot
ExecStart=/bin/sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/enabled'
ExecStart=/bin/sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/defrag'

[Install]
WantedBy=basic.target
EOF

systemctl enable disable-thp.service
systemctl start disable-thp.service

3.2.2 NUMA优化

# 查看NUMA拓扑
numactl --hardware

# 使用numactl绑定内存和CPU
# 示例:将MySQL绑定到节点0
numactl --cpunodebind=0 --membind=0 mysqld_safe --defaults-file=/etc/my.cnf

# 在systemd服务中配置
cat > /etc/systemd/system/mysqld.service.d/numa.conf << 'EOF'
[Service]
ExecStart=
ExecStart=/usr/bin/numactl --cpunodebind=0 --membind=0 /usr/sbin/mysqld --daemonize --pid-file=/run/mysqld/mysqld.pid
EOF

3.3 I/O资源优化

3.3.1 磁盘I/O调度器

# 查看所有块设备的调度器
for dev in $(lsblk -d -o NAME | grep -v NAME); do
    echo "$dev: $(cat /sys/block/$dev/queue/scheduler 2>/dev/null)"
done

# 批量设置调度器(SSD使用none,HDD使用deadline)
for dev in $(lsblk -d -o NAME | grep -v NAME); do
    if [[ $(cat /sys/block/$dev/queue/rotational) -eq 0 ]]; then
        echo "none" > /sys/block/$dev/queue/scheduler
    else
        echo "deadline" > /sys/block/$dev/queue/scheduler
    fi
done

3.3.2 I/O队列深度优化

# 查看当前队列深度
cat /sys/block/sda/queue/nr_requests

# 增加队列深度(适用于高并发I/O)
echo 256 > /sys/block/sda/queue/nr_requests

# 对于NVMe设备,优化队列数
echo 8 > /sys/block/nvme0n1/queue/nr_hw_queues

# 永久化配置
cat > /etc/udev/rules.d/60-io-queue.rules << 'EOF'
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/nr_requests}="256"
ACTION=="add|change", KERNEL=="nvme[0-9]*", ATTR{queue/nr_hw_queues}="8"
EOF

四、网络性能优化

4.1 网络接口优化

4.1.1 多队列网卡优化

# 查看网卡队列
ethtool -l eth0

# 设置队列数(根据CPU核心数调整)
ethtool -L eth0 combined 8

# 启用RSS(Receive Side Scaling)
ethtool -K eth0 rxhash on

# 设置IRQ亲和性
# 查看中断号
cat /proc/interrupts | grep eth0

# 将中断绑定到特定CPU(示例:绑定到CPU 4-7)
for irq in $(cat /proc/interrupts | grep eth0 | awk '{print $1}' | tr -d ':'); do
    echo 4-7 > /proc/irq/$irq/smp_affinity_list
done

4.1.2 网络缓冲区优化

# 查看当前设置
ethtool -g eth0

# 设置环形缓冲区(适用于高吞吐量)
ethtool -G eth0 rx 4096 tx 4096

# 永久化配置
cat > /etc/systemd/system/eth0-tuning.service << 'EOF'
[Unit]
Description=Network Interface Tuning
After=network.target

[Service]
Type=oneshot
ExecStart=/usr/sbin/ethtool -G eth0 rx 4096 tx 4096
ExecStart=/usr/sbin/ethtool -K eth0 rxhash on

[Install]
WantedBy=multi-user.target
EOF

4.2 TCP协议栈优化

4.2.1 连接跟踪优化

# 查看连接跟踪表
conntrack -L | wc -l

# 优化连接跟踪参数
cat > /etc/sysctl.d/99-conntrack.conf << 'EOF'
# 增加连接跟踪表大小
net.netfilter.nf_conntrack_max = 1000000

# 优化TCP连接超时
net.netfilter.nf_conntrack_tcp_timeout_established = 7200
net.netfilter.nf_conntrack_tcp_timeout_close_wait = 60
net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 45

# 优化UDP连接超时
net.netfilter.nf_conntrack_udp_timeout = 30
net.netfilter.nf_conntrack_udp_timeout_stream = 180
EOF

sysctl -p /etc/sysctl.d/99-conntrack.conf

4.2.2 TCP快速打开(TFO)

# 启用TCP快速打开
echo 3 > /proc/sys/net/ipv4/tcp_fastopen

# 永久化配置
echo "net.ipv4.tcp_fastopen = 3" >> /etc/sysctl.d/99-network.conf

# 验证TFO状态
ss -lnt | grep -E "LISTEN.*:80|LISTEN.*:443"

4.3 负载均衡与连接复用

4.3.1 使用HAProxy进行连接复用

# 安装HAProxy
sudo dnf install -y haproxy

# 配置HAProxy(示例:HTTP负载均衡)
cat > /etc/haproxy/haproxy.cfg << 'EOF'
global
    maxconn 100000
    tune.ssl.default-dh-param 2048

defaults
    mode http
    timeout connect 5s
    timeout client 30s
    timeout server 30s
    option httplog
    option dontlognull
    option http-server-close
    option forwardfor

frontend web_frontend
    bind *:80
    default_backend web_servers

backend web_servers
    balance roundrobin
    option httpchk GET /health
    server web1 192.168.1.10:80 check maxconn 1000
    server web2 192.168.1.11:80 check maxconn 1000
    server web3 192.168.1.12:80 check maxconn 1000
EOF

# 启用并启动HAProxy
systemctl enable haproxy
systemctl start haproxy

五、存储I/O优化

5.1 文件系统优化

5.1.1 XFS文件系统优化

# 查看XFS挂载选项
mount | grep xfs

# 优化XFS参数(适用于数据库)
cat > /etc/fstab << 'EOF'
/dev/sda1 /data xfs defaults,noatime,nodiratime,logbufs=8,logbsize=256k,allocsize=64m 0 0
EOF

# 重新挂载
mount -o remount /data

# 调整XFS分配策略
xfs_io -c "falloc 0 1G" /data/testfile
xfs_io -c "sync" /data/testfile

5.1.2 EXT4文件系统优化

# 查看EXT4挂载选项
mount | grep ext4

# 优化EXT4参数
cat > /etc/fstab << 'EOF'
/dev/sdb1 /var/log ext4 defaults,noatime,nodiratime,data=writeback,barrier=0 0 0
EOF

# 调整EXT4日志大小
tune2fs -J size=128 /dev/sdb1

# 启用discard(TRIM)支持
tune2fs -o discard /dev/sdb1

5.2 I/O调度器优化

5.2.1 针对SSD的优化

# SSD优化配置
cat > /etc/udev/rules.d/60-ssd.rules << 'EOF'
# 禁用I/O调度器(SSD不需要)
ACTION=="add|change", KERNEL=="nvme[0-9]*", ATTR{queue/scheduler}="none"
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="none"

# 启用TRIM支持
ACTION=="add|change", KERNEL=="nvme[0-9]*", ATTR{queue/discard_max_bytes}="2147483648"
EOF

# 应用规则
udevadm control --reload-rules
udevadm trigger

5.2.2 针对HDD的优化

# HDD优化配置
cat > /etc/udev/rules.d/60-hdd.rules << 'EOF'
# 使用deadline调度器
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="1", ATTR{queue/scheduler}="deadline"

# 增加队列深度
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="1", ATTR{queue/nr_requests}="256"
EOF

5.3 RAID优化

5.3.1 软件RAID优化

# 查看RAID状态
cat /proc/mdstat

# 调整RAID条带大小(适用于大文件I/O)
mdadm --grow /dev/md0 --chunk-size=512

# 优化RAID读写策略
echo "md0" > /sys/block/md0/md/sync_action  # 设置为"resync"或"recover"
echo "md0" > /sys/block/md0/md/sync_completed  # 查看进度

# 调整RAID缓存策略
echo 1024 > /sys/block/md0/md/stripe_cache_size

5.3.2 LVM优化

# 查看LVM配置
lvs -o +segtype

# 调整LVM条带数(适用于多磁盘)
lvcreate --type striped --stripes 4 --size 100G --name lv_data vg_data

# 调整LVM缓存(适用于频繁访问的小文件)
lvcreate --type cache --size 10G --name lv_cache vg_data
lvconvert --type cache --cache-pool vg_data/lv_cache vg_data/lv_data

六、应用层优化

6.1 Web服务器优化(Nginx)

6.1.1 Nginx配置优化

# /etc/nginx/nginx.conf
worker_processes auto;  # 自动设置为CPU核心数
worker_rlimit_nofile 65536;  # 文件描述符限制

events {
    worker_connections 4096;  # 每个worker的连接数
    use epoll;  # 使用epoll事件模型
    multi_accept on;  # 一次接受多个连接
}

http {
    # 连接复用
    keepalive_timeout 65;
    keepalive_requests 1000;
    
    # 缓冲区优化
    client_body_buffer_size 128k;
    client_max_body_size 10m;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 8k;
    
    # Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/xml+rss
        application/json;
    
    # 缓存配置
    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;
    
    # TCP优化
    tcp_nopush on;
    tcp_nodelay on;
    
    # 超时设置
    proxy_connect_timeout 60s;
    proxy_send_timeout 60s;
    proxy_read_timeout 60s;
}

6.1.2 Nginx性能测试

# 使用ab测试(Apache Bench)
ab -n 10000 -c 100 -k http://localhost/

# 使用wrk测试(更现代的工具)
wrk -t12 -c400 -d30s http://localhost/

# 使用nginx自带的性能监控
nginx -V 2>&1 | grep -o with-http_stub_status_module
# 如果启用,配置location /nginx_status
location /nginx_status {
    stub_status;
    allow 127.0.0.1;
    deny all;
}

6.2 数据库优化(MySQL/MariaDB)

6.2.1 MySQL配置优化

# /etc/my.cnf.d/server.cnf
[mysqld]
# 内存配置(根据总内存调整)
innodb_buffer_pool_size = 16G  # 通常设置为总内存的50-70%
innodb_log_file_size = 2G
innodb_log_buffer_size = 64M
innodb_flush_log_at_trx_commit = 2  # 平衡性能与数据安全

# 连接配置
max_connections = 500
thread_cache_size = 50
table_open_cache = 2000

# 查询缓存(MySQL 8.0已移除,MariaDB仍支持)
query_cache_type = 1
query_cache_size = 128M

# InnoDB优化
innodb_flush_method = O_DIRECT
innodb_file_per_table = 1
innodb_flush_neighbors = 0  # SSD优化
innodb_read_io_threads = 8
innodb_write_io_threads = 8

# 日志优化
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2
log_queries_not_using_indexes = 1

6.2.2 MySQL性能分析

# 启用性能模式
mysql -e "SET GLOBAL performance_schema=ON;"

# 查看慢查询
mysql -e "SELECT * FROM mysql.slow_log ORDER BY query_time DESC LIMIT 10;"

# 使用pt-query-digest分析慢查询日志
pt-query-digest /var/log/mysql/slow.log > /tmp/query_analysis.txt

# 使用Percona Toolkit进行诊断
pt-mysql-summary --user=root --password

6.3 Java应用优化

6.3.1 JVM参数优化

# Java 8+ 优化参数示例
java -Xms4G -Xmx4G \  # 堆内存设置(初始和最大)
     -XX:+UseG1GC \    # 使用G1垃圾回收器
     -XX:MaxGCPauseMillis=200 \  # 目标最大GC暂停时间
     -XX:InitiatingHeapOccupancyPercent=45 \  # 触发GC的堆占用率
     -XX:ConcGCThreads=4 \  # 并发GC线程数
     -XX:ParallelGCThreads=8 \  # 并行GC线程数
     -XX:+UseStringDeduplication \  # 字符串去重
     -XX:+OptimizeStringConcat \  # 优化字符串连接
     -XX:+UseCompressedOops \  # 压缩对象指针
     -XX:+UseCompressedClassPointers \
     -XX:+UseLargePages \  # 使用大页内存
     -XX:+UseNUMA \  # NUMA优化
     -XX:+UseThreadPriorities \  # 线程优先级
     -XX:ThreadPriorityPolicy=1 \
     -Djava.net.preferIPv4Stack=true \  # 优先使用IPv4
     -Djava.awt.headless=true \  # 无头模式
     -Dfile.encoding=UTF-8 \
     -Duser.timezone=UTC \
     -jar your-application.jar

6.3.2 JVM监控与调优

# 使用jstat监控GC
jstat -gcutil <pid> 1000

# 使用jmap生成堆转储
jmap -dump:format=b,file=/tmp/heap.hprof <pid>

# 使用jstack分析线程
jstack <pid> > /tmp/thread_dump.txt

# 使用VisualVM远程监控
# 启用JMX远程访问
java -Dcom.sun.management.jmxremote \
     -Dcom.sun.management.jmxremote.port=9010 \
     -Dcom.sun.management.jmxremote.authenticate=false \
     -Dcom.sun.management.jmxremote.ssl=false \
     -jar your-application.jar

6.4 容器化应用优化

6.4.1 Docker容器优化

# 优化Docker守护进程配置
cat > /etc/docker/daemon.json << 'EOF'
{
  "storage-driver": "overlay2",
  "storage-opts": [
    "overlay2.override_kernel_check=true"
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "default-ulimits": {
    "nofile": {
      "Name": "nofile",
      "Hard": 65536,
      "Soft": 65536
    }
  },
  "exec-opts": ["native.cgroupdriver=cgroupfs"],
  "cgroup-parent": "docker.slice"
}
EOF

# 重启Docker
systemctl restart docker

# 运行优化后的容器
docker run -d \
  --name optimized-app \
  --memory=2g \
  --memory-swap=2g \
  --cpus=2.0 \
  --cpu-shares=512 \
  --ulimit nofile=65536:65536 \
  --restart unless-stopped \
  your-image:latest

6.4.2 Kubernetes Pod优化

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: optimized-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: optimized-app
  template:
    metadata:
      labels:
        app: optimized-app
    spec:
      containers:
      - name: app
        image: your-image:latest
        resources:
          requests:
            memory: "1Gi"
            cpu: "500m"
          limits:
            memory: "2Gi"
            cpu: "1000m"
        env:
        - name: JAVA_OPTS
          value: "-Xms1G -Xmx1G -XX:+UseG1GC"
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5
        securityContext:
          runAsUser: 1000
          runAsGroup: 1000
          readOnlyRootFilesystem: true
          allowPrivilegeEscalation: false
      nodeSelector:
        disktype: ssd
      tolerations:
      - key: "dedicated"
        operator: "Equal"
        value: "app"
        effect: "NoSchedule"

七、监控与持续优化

7.1 实时监控系统

7.1.1 Prometheus + Grafana监控

# 安装Prometheus
sudo dnf install -y prometheus

# 配置Prometheus(/etc/prometheus/prometheus.yml)
cat > /etc/prometheus/prometheus.yml << 'EOF'
global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: 'node'
    static_configs:
      - targets: ['localhost:9100']
  - job_name: 'nginx'
    static_configs:
      - targets: ['localhost:9113']
  - job_name: 'mysql'
    static_configs:
      - targets: ['localhost:9104']
EOF

# 安装Node Exporter
sudo dnf install -y node_exporter
systemctl enable node_exporter
systemctl start node_exporter

# 安装Grafana
sudo dnf install -y grafana
systemctl enable grafana-server
systemctl start grafana-server

7.1.2 自定义监控脚本

#!/bin/bash
# /usr/local/bin/performance_monitor.sh

# 收集系统指标
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
MEM_USAGE=$(free | grep Mem | awk '{printf "%.2f", $3/$2 * 100.0}')
DISK_IO=$(iostat -x 1 2 | tail -n +4 | awk '{sum+=$14} END {print sum/NR}')
NET_IO=$(cat /proc/net/dev | grep eth0 | awk '{sum+=$2+$10} END {print sum/1024/1024}')

# 输出到日志
echo "$(date '+%Y-%m-%d %H:%M:%S') CPU:$CPU_USAGE% MEM:$MEM_USAGE% DISK_IO:$DISK_IO% NET_IO:${NET_IO}MB/s" >> /var/log/performance.log

# 发送到监控系统(示例:发送到InfluxDB)
curl -i -XPOST 'http://localhost:8086/write?db=performance' \
  --data-binary "system,host=server1 cpu=$CPU_USAGE,mem=$MEM_USAGE,disk=$DISK_IO,net=$NET_IO"

7.2 自动化调优工具

7.2.1 使用tuned进行动态调优

# 安装tuned
sudo dnf install -y tuned

# 查看可用配置文件
tuned-adm list

# 应用配置文件
tuned-adm profile virtual-guest  # 虚拟化环境
tuned-adm profile throughput-performance  # 高吞吐量
tuned-adm profile latency-performance  # 低延迟

# 创建自定义配置文件
mkdir -p /etc/tuned/custom-profile
cat > /etc/tuned/custom-profile/tuned.conf << 'EOF'
[main]
summary=Custom performance profile

[cpu]
governor=performance
energy_perf_bias=performance

[vm]
swappiness=10
dirty_ratio=15
dirty_background_ratio=5

[net]
net.core.rmem_max=134217728
net.core.wmem_max=134217728
EOF

# 应用自定义配置
tuned-adm profile custom-profile

7.2.2 使用autotune进行自动优化

# 安装autotune(需要EPEL仓库)
sudo dnf install -y epel-release
sudo dnf install -y autotune

# 运行自动优化
autotune --profile web-server --output /etc/sysctl.d/99-autotune.conf

# 查看建议
autotune --profile web-server --dry-run

7.3 性能测试与基准测试

7.3.1 系统级基准测试

# CPU基准测试
sysbench cpu --cpu-max-prime=20000 run

# 内存基准测试
sysbench memory --memory-block-size=1M --memory-total-size=10G run

# 磁盘I/O基准测试
sysbench fileio --file-total-size=5G --file-test-mode=rndrw --time=30 --threads=8 run

# 网络基准测试
# 服务端
iperf3 -s -p 5201
# 客户端
iperf3 -c server_ip -p 5201 -t 30 -P 8

7.3.2 应用级基准测试

# Web服务器基准测试
# 使用wrk
wrk -t12 -c400 -d30s --latency http://localhost/

# 使用siege
siege -c 100 -t 30s -f urls.txt

# 数据库基准测试
# sysbench OLTP测试
sysbench oltp_read_write --table-size=1000000 --threads=16 --time=60 run

# 使用mysqlslap
mysqlslap --auto-generate-sql --concurrency=50 --iterations=5 --number-of-queries=1000

八、故障排查与优化案例

8.1 常见性能问题排查

8.1.1 高CPU使用率

# 使用perf分析CPU热点
sudo perf top -p $(pgrep -f nginx)

# 使用pidstat监控进程
pidstat -u 1 -p $(pgrep -f nginx)

# 使用strace跟踪系统调用
strace -c -p $(pgrep -f nginx) -e trace=network

8.1.2 内存泄漏排查

# 使用smem查看内存分布
smem -k -P nginx

# 使用pmap查看进程内存映射
pmap -x $(pgrep -f nginx) | tail -n 1

# 使用valgrind检测内存泄漏(开发环境)
valgrind --leak-check=full --track-origins=yes ./your-application

8.1.3 I/O瓶颈排查

# 使用iotop监控I/O
iotop -o -p $(pgrep -f nginx)

# 使用bpftrace分析I/O
bpftrace -e 'tracepoint:block:block_rq_complete { @[comm] = count(); }'

# 使用iostat详细分析
iostat -xmt 1

8.2 优化案例:电商网站性能提升

8.2.1 问题描述

  • 峰值时段响应时间从200ms上升到2s
  • CPU使用率超过80%
  • 数据库连接池耗尽

8.2.2 优化步骤

# 1. 系统级优化
# 调整内核参数
echo "net.core.somaxconn = 65536" >> /etc/sysctl.d/99-network.conf
echo "net.ipv4.tcp_max_syn_backlog = 65536" >> /etc/sysctl.d/99-network.conf
sysctl -p

# 2. Nginx优化
# 增加worker_connections
sed -i 's/worker_connections 1024/worker_connections 4096/' /etc/nginx/nginx.conf

# 3. 数据库优化
# 调整MySQL连接池
mysql -e "SET GLOBAL max_connections = 500;"
mysql -e "SET GLOBAL thread_cache_size = 50;"

# 4. 应用层优化
# 增加缓存
# 在应用代码中添加Redis缓存
redis-cli config set maxmemory 4gb
redis-cli config set maxmemory-policy allkeys-lru

# 5. 监控验证
# 使用ab测试
ab -n 10000 -c 100 -k http://localhost/

8.2.3 优化效果

  • 响应时间从2s降至150ms
  • CPU使用率从80%降至45%
  • 数据库连接池使用率从100%降至60%

九、总结与最佳实践

9.1 优化原则

  1. 测量优先:优化前必须建立性能基线
  2. 渐进式调整:每次只调整一个参数,观察效果
  3. 监控持续:优化后持续监控,防止性能回退
  4. 文档记录:记录所有优化决策和效果

9.2 推荐配置组合

# 高吞吐量Web服务器配置
# /etc/sysctl.d/99-high-throughput.conf
net.core.rmem_max = 134217728
net.core.wmem_max = 134217728
net.ipv4.tcp_rmem = 4096 87380 134217728
net.ipv4.tcp_wmem = 4096 65536 134217728
net.ipv4.tcp_max_syn_backlog = 65536
net.core.somaxconn = 65536
net.ipv4.tcp_congestion_control = bbr
vm.swappiness = 10
vm.dirty_ratio = 15
vm.dirty_background_ratio = 5

9.3 持续优化流程

  1. 监控:建立全面的监控体系
  2. 分析:定期分析性能数据,识别瓶颈
  3. 优化:针对瓶颈实施优化措施
  4. 验证:测试优化效果,确保无副作用
  5. 迭代:重复上述过程,持续改进

通过本文提供的全方位调优策略,您可以系统性地提升AlmaLinux服务器的性能。记住,性能优化是一个持续的过程,需要根据实际业务负载和硬件环境不断调整和优化。