最佳实践 Featured
云服务器性能优化实战
从操作系统、应用架构、数据库等多个方面介绍云服务器性能优化的实用技巧。
igwen6w
为什么需要性能优化
云服务器性能优化可以提高资源利用率,降低成本,改善用户体验。合理的优化可以让同样的配置支撑更多的业务。
评估现状
性能指标
关键指标:
- CPU使用率
- 内存使用率
- 磁盘I/O
- 网络吞吐
- 响应时间
监控工具:
# 系统监控
top
htop
vmstat
iostat
# 性能分析
perf
strace
tcpdump
操作系统优化
1. 内核参数优化
/etc/sysctl.conf 配置:
# 网络优化
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.tcp_max_syn_backlog = 8192
# 文件描述符
fs.file-max = 655350
# 共享内存
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
应用配置:
sudo sysctl -p
2. 文件系统优化
选择合适的文件系统:
- ext4 - 稳定可靠,通用性好
- xfs - 大文件性能好,适合大容量存储
- btrfs - 支持快照和压缩
挂载选项:
# /etc/fstab
/dev/sdb1 /data ext4 defaults,noatime,nodiratime 0 0
3. 磁盘调度算法
# 查看当前调度器
cat /sys/block/sda/queue/scheduler
# 临时修改
echo deadline > /sys/block/sda/queue/scheduler
# 永久修改(grub配置)
# /etc/default/grub
GRUB_CMDLINE_LINUX_DEFAULT="quiet elevator=deadline"
应用优化
1. Web服务器优化
Nginx优化:
# nginx.conf
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 10240;
use epoll;
multi_accept on;
}
http {
# 基础优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss;
# 缓存配置
open_file_cache max=100000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
}
Apache优化:
# httpd.conf
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
2. PHP优化
PHP-FPM配置:
# php-fpm.conf
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
# php.ini
memory_limit = 256M
max_execution_time = 30
max_input_time = 60
post_max_size = 20M
upload_max_filesize = 20M
# OPcache
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
3. Node.js优化
集群模式:
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
// Worker processes
require('./app');
}
性能优化:
// 启用压缩
const compression = require('compression');
app.use(compression());
// 静态文件缓存
app.use(express.static('public', {
maxAge: '1d',
lastModified: true,
etag: true
}));
4. Java应用优化
JVM参数:
java -Xms2g -Xmx2g \
-XX:+UseG1GC \
-XX:MaxGCPauseMillis=200 \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/var/log/app/ \
-jar app.jar
数据库优化
1. MySQL优化
配置优化:
# my.cnf
[mysqld]
# 连接数
max_connections = 500
# 缓冲区
innodb_buffer_pool_size = 4G
key_buffer_size = 256M
table_open_cache = 2000
# 查询缓存
query_cache_size = 128M
query_cache_type = 1
# 日志
slow_query_log = 1
long_query_time = 2
查询优化:
-- 创建索引
CREATE INDEX idx_user_email ON users(email);
-- 优化查询
EXPLAIN SELECT * FROM users WHERE email = 'user@example.com';
-- 分析表
ANALYZE TABLE users;
2. Redis优化
配置优化:
# redis.conf
maxmemory 2gb
maxmemory-policy allkeys-lru
# 持久化
save 900 1
save 300 10
save 60 10000
appendonly yes
appendfsync everysec
使用技巧:
# 选择合适的数据库
SELECT 1
# 设置过期时间
SETEX key 3600 value
# 批量操作
MGET key1 key2 key3
缓存策略
1. 应用层缓存
内存缓存:
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 600 });
// 设置缓存
cache.set('key', 'value');
// 获取缓存
const value = cache.get('key');
2. 分布式缓存
Redis缓存:
const redis = require('redis');
const client = redis.createClient();
async function getData(key) {
// 先查缓存
const cached = await client.get(key);
if (cached) return JSON.parse(cached);
// 缓存未命中,查数据库
const data = await db.query('SELECT * FROM table WHERE id = ?', [key]);
// 写入缓存
await client.setex(key, 3600, JSON.stringify(data));
return data;
}
3. CDN缓存
HTTP缓存头:
// Express.js
app.use(express.static('public', {
maxAge: '1d',
etag: true,
lastModified: true
}));
// 手动设置
res.set('Cache-Control', 'public, max-age=86400');
res.set('Expires', new Date(Date.now() + 86400000).toUTCString());
负载均衡
1. Nginx负载均衡
upstream backend {
least_conn;
server backend1.example.com weight=3;
server backend2.example.com;
server backend3.example.com backup;
}
server {
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
2. HAProxy配置
backend web_servers
balance roundrobin
server web1 10.0.0.1:80 check
server web2 10.0.0.2:80 check
server web3 10.0.0.3:80 check
监控和诊断
1. 应用监控
PM2监控:
pm2 start app.js -i max
pm2 monit
自定义监控:
const express = require('express');
const app = express();
app.get('/health', (req, res) => {
res.json({
status: 'ok',
uptime: process.uptime(),
memory: process.memoryUsage(),
cpu: process.cpuUsage()
});
});
2. 日志管理
日志轮转:
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
性能测试
1. 压力测试
Apache Bench:
ab -n 1000 -c 10 https://example.com/
wrk:
wrk -t12 -c400 -d30s https://example.com/
hey:
hey -n 1000 -c 10 https://example.com/
2. 性能分析
Node.js:
node --prof app.js
node --prof-process isolate-0xnnnnnnnnnnnn-v8.log > profile.txt
Java:
# 生成堆转储
jmap -dump:format=b,file=heap.bin <pid>
# 分析堆转储
jhat heap.bin
总结
性能优化是一个持续的过程,需要:
- 监控 - 建立完善的监控体系
- 分析 - 找出性能瓶颈
- 优化 - 有针对性地进行优化
- 测试 - 验证优化效果
- 迭代 - 持续改进优化方案
记住:过早优化是万恶之源,先让代码工作,再让它快。
相关阅读: