乐闻世界logo
搜索文章和话题

面试题手册

Nginx 如何进行监控和运维?有哪些监控工具?

Nginx 如何进行监控和运维?有哪些监控工具?Nginx 的监控和运维对于保证服务稳定性和性能至关重要。合理的监控可以及时发现和解决问题。内置状态监控:# 启用 stub_status 模块server { listen 80; server_name localhost; location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; }}状态信息说明:Active connections:当前活动连接数accepts:已接受的连接总数handled:已处理的连接总数requests:已处理的请求总数Reading:正在读取请求头的连接数Writing:正在发送响应的连接数Waiting:空闲连接数自定义监控端点:server { listen 80; server_name localhost; # 健康检查 location /health { access_log off; return 200 "OK\n"; add_header Content-Type text/plain; } # 就绪检查 location /ready { access_log off; # 检查后端连接 proxy_pass http://backend/health; proxy_intercept_errors off; } # 版本信息 location /version { access_log off; return 200 "Nginx/1.21.0\n"; add_header Content-Type text/plain; }}日志监控:# 自定义日志格式log_format monitoring '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' 'rt=$request_time uct="$upstream_connect_time" ' 'uht="$upstream_header_time" urt="$upstream_response_time" ' 'cache=$upstream_cache_status';server { listen 80; server_name example.com; access_log /var/log/nginx/monitoring.log monitoring; location / { proxy_pass http://backend; }}Prometheus 监控:# 安装 nginx-prometheus-exporter# https://github.com/nginxinc/nginx-prometheus-exporter# 配置 Nginxserver { listen 80; server_name localhost; location /metrics { proxy_pass http://localhost:9113/metrics; access_log off; allow 127.0.0.1; deny all; }}Grafana + Prometheus 监控:# prometheus.ymlglobal: scrape_interval: 15sscrape_configs: - job_name: 'nginx' static_configs: - targets: ['localhost:9113']ELK Stack 监控:# JSON 格式日志log_format json_combined escape=json '{' '"time_local":"$time_local",' '"remote_addr":"$remote_addr",' '"remote_user":"$remote_user",' '"request":"$request",' '"status":"$status",' '"body_bytes_sent":"$body_bytes_sent",' '"request_time":"$request_time",' '"http_referrer":"$http_referer",' '"http_user_agent":"$http_user_agent"''}';server { listen 80; server_name example.com; access_log /var/log/nginx/access.log json_combined; location / { proxy_pass http://backend; }}Zabbix 监控:# 安装 Zabbix Agent# 配置监控项# nginx_status[accepts]# nginx_status[handled]# nginx_status[requests]# nginx_status[reading]# nginx_status[writing]# nginx_status[waiting]性能监控指标:# 启用详细日志log_format performance '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' 'rt=$request_time ' 'uct=$upstream_connect_time ' 'uht=$upstream_header_time ' 'urt=$upstream_response_time ' 'cache=$upstream_cache_status';server { listen 80; server_name example.com; access_log /var/log/nginx/performance.log performance; location / { proxy_pass http://backend; }}告警配置:# 基于日志的告警map $status $alert_level { ~^[5] critical; ~^[4] warning; default ok;}server { listen 80; server_name example.com; access_log /var/log/nginx/access.log performance; location / { proxy_pass http://backend; # 添加告警头 add_header X-Alert-Level $alert_level; }}自动化运维脚本:#!/bin/bash# nginx_monitor.sh# 检查 Nginx 状态check_nginx_status() { if ! curl -f http://localhost/nginx_status > /dev/null 2>&1; then echo "Nginx status page is not accessible" return 1 fi return 0}# 检查进程check_nginx_process() { if ! pgrep -x nginx > /dev/null; then echo "Nginx process is not running" return 1 fi return 0}# 检查端口check_nginx_port() { if ! netstat -tlnp | grep :80 > /dev/null; then echo "Nginx is not listening on port 80" return 1 fi return 0}# 主函数main() { check_nginx_status check_nginx_process check_nginx_port echo "All checks passed"}main运维命令:# 重载配置(不中断服务)nginx -s reload# 优雅停止nginx -s quit# 快速停止nginx -s stop# 重新打开日志文件nginx -s reopen# 测试配置nginx -t# 查看版本nginx -v# 查看编译参数nginx -V日志轮转:# /etc/logrotate.d/nginx/var/log/nginx/*.log { daily missingok rotate 14 compress delaycompress notifempty create 0640 nginx adm sharedscripts postrotate [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid` endscript}完整监控配置示例:user nginx;worker_processes auto;http { # 日志格式 log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"'; log_format performance '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' 'rt=$request_time ' 'uct=$upstream_connect_time ' 'uht="$upstream_header_time" ' 'urt="$upstream_response_time" ' 'cache=$upstream_cache_status'; log_format json_combined escape=json '{' '"time_local":"$time_local",' '"remote_addr":"$remote_addr",' '"remote_user":"$remote_user",' '"request":"$request",' '"status":"$status",' '"body_bytes_sent":"$body_bytes_sent",' '"request_time":"$request_time",' '"http_referrer":"$http_referer",' '"http_user_agent":"$http_user_agent"' '}'; # 主站点 server { listen 80; server_name example.com; root /var/www/html; index index.html; # 性能日志 access_log /var/log/nginx/performance.log performance; error_log /var/log/nginx/error.log warn; # 监控端点 location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; } location /health { access_log off; return 200 "OK\n"; add_header Content-Type text/plain; } location /ready { access_log off; proxy_pass http://backend/health; proxy_intercept_errors off; } location /metrics { proxy_pass http://localhost:9113/metrics; access_log off; allow 127.0.0.1; deny all; } location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }}监控工具推荐:Prometheus + Grafana:强大的监控和可视化平台ELK Stack:日志收集、存储和分析Zabbix:企业级监控系统Nagios:成熟的监控解决方案Datadog:云端监控服务New Relic:应用性能监控AppDynamics:应用性能管理运维最佳实践:全面监控:监控性能、日志、资源使用及时告警:设置合理的告警阈值定期备份:备份配置和重要数据自动化运维:使用脚本和工具自动化运维文档记录:详细记录运维操作和问题定期演练:定期进行故障演练性能优化:持续监控和优化性能安全审计:定期进行安全检查容量规划:根据业务增长进行容量规划持续改进:根据监控数据持续改进
阅读 0·2月21日 16:57

Nginx 如何进行性能调优?有哪些关键参数?

Nginx 如何进行性能调优?有哪些关键参数?Nginx 性能调优是一个系统工程,需要从多个维度进行优化。合理的配置可以显著提升 Nginx 的处理能力和响应速度。核心配置优化:# 全局配置user nginx;worker_processes auto; # 自动设置为 CPU 核心数worker_rlimit_nofile 100000; # 文件描述符限制worker_cpu_affinity auto; # CPU 亲和性绑定events { worker_connections 65535; # 每个 worker 的最大连接数 use epoll; # Linux 使用 epoll multi_accept on; # 同时接受多个连接 accept_mutex off; # 关闭互斥锁,减少锁竞争}http { # 基础优化 sendfile on; # 启用高效文件传输 tcp_nopush on; # 优化数据包发送 tcp_nodelay on; # 禁用 Nagle 算法 keepalive_timeout 65; # 长连接超时 keepalive_requests 100; # 长连接最大请求数 # 缓冲区优化 client_body_buffer_size 128k; # 客户端请求体缓冲区 client_max_body_size 10m; # 最大请求体大小 client_header_buffer_size 1k; # 客户端请求头缓冲区 large_client_header_buffers 4 4k; # 大请求头缓冲区 # 输出缓冲 output_buffers 1 32k; # 输出缓冲区 postpone_output 1460; # 延迟输出 # 文件缓存 open_file_cache max=100000 inactive=20s; # 文件描述符缓存 open_file_cache_valid 30s; # 缓存验证间隔 open_file_cache_min_uses 2; # 最小使用次数 open_file_cache_errors on; # 缓存错误信息 # 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; gzip_disable "msie6";}Worker 进程优化:# 根据 CPU 核心数设置worker_processes auto;# 绑定 CPU 核心(手动设置)# 假设 4 核 CPUworker_processes 4;worker_cpu_affinity 0001 0010 0100 1000;# 设置工作进程优先级worker_priority -5; # -20 到 19,数值越小优先级越高连接优化:events { # 增加连接数 worker_connections 65535; # 同时接受多个连接 multi_accept on; # 关闭互斥锁(高并发时) accept_mutex off; # 使用高效的事件模型 use epoll; # Linux # use kqueue; # BSD/macOS}http { # 长连接优化 keepalive_timeout 65; keepalive_requests 100; # 上游服务器长连接 upstream backend { server 192.168.1.100:8080; keepalive 32; # 保持 32 个空闲连接 } # 代理超时设置 proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s;}缓冲区优化:http { # 客户端缓冲区 client_body_buffer_size 128k; client_max_body_size 10m; client_header_buffer_size 1k; large_client_header_buffers 4 4k; # 代理缓冲区 proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 4k; proxy_busy_buffers_size 8k; # FastCGI 缓冲区 fastcgi_buffer_size 4k; fastcgi_buffers 8 4k; # 输出缓冲 output_buffers 1 32k; postpone_output 1460;}文件操作优化:http { # 文件缓存 open_file_cache max=100000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on; # 高效文件传输 sendfile on; tcp_nopush on; tcp_nodelay on; # 直接 I/O(大文件) # directio 4m;}压缩优化:http { gzip on; gzip_vary on; gzip_min_length 1024; # 最小压缩文件大小 gzip_comp_level 6; # 压缩级别 1-9 gzip_buffers 16 8k; # 压缩缓冲区 gzip_http_version 1.1; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/rss+xml application/atom+xml image/svg+xml; gzip_disable "msie6"; # 静态资源预压缩 gzip_static on;}日志优化:http { # 自定义日志格式 log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' 'rt=$request_time uct="$upstream_connect_time" ' 'uht="$upstream_header_time" urt="$upstream_response_time"'; # 访问日志 access_log /var/log/nginx/access.log main buffer=32k flush=5s; # 错误日志 error_log /var/log/nginx/error.log warn; # 关闭静态资源日志 location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2)$ { access_log off; }}SSL/TLS 优化:server { listen 443 ssl http2; # SSL 会话缓存 ssl_session_cache shared:SSL:50m; ssl_session_timeout 1d; ssl_session_tickets off; # SSL 缓冲区 ssl_buffer_size 4k; # 协议和加密套件 ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256; ssl_prefer_server_ciphers on; # OCSP Stapling ssl_stapling on; ssl_stapling_verify on;}系统级优化:# /etc/sysctl.conf# 文件描述符fs.file-max = 1000000# TCP 参数net.ipv4.tcp_max_tw_buckets = 6000net.ipv4.tcp_sack = 1net.ipv4.tcp_window_scaling = 1net.ipv4.tcp_rmem = 4096 87380 4194304net.ipv4.tcp_wmem = 4096 65536 4194304net.core.rmem_max = 16777216net.core.wmem_max = 16777216net.core.netdev_max_backlog = 262144net.ipv4.tcp_max_syn_backlog = 262144net.ipv4.tcp_fin_timeout = 30net.ipv4.tcp_keepalive_time = 1200net.ipv4.tcp_tw_reuse = 1# 应用配置sysctl -p用户限制:# /etc/security/limits.confnginx soft nofile 65535nginx hard nofile 65535监控和诊断:# 状态监控location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all;}# 请求追踪location /debug { add_header X-Request-ID $request_id; add_header X-Upstream-Addr $upstream_addr;}性能测试工具:# wrk 压力测试wrk -t12 -c4000 -d30s http://example.com/# ab 压力测试ab -n 10000 -c 1000 http://example.com/# siege 压力测试siege -c 100 -t 60S http://example.com/关键性能指标:QPS(每秒查询数):衡量处理能力响应时间:平均、P95、P99并发连接数:当前活动连接错误率:4xx、5xx 错误比例CPU 使用率:不应持续超过 70%内存使用:监控内存占用磁盘 I/O:监控读写性能调优建议:渐进式调优:每次只调整一个参数,观察效果基准测试:调优前后进行性能对比监控指标:持续关注关键性能指标日志分析:分析访问日志发现瓶颈定期审查:定期检查配置是否合理
阅读 0·2月21日 16:57

Nginx 如何进行安全配置?有哪些安全最佳实践?

Nginx 如何进行安全配置?有哪些安全最佳实践?Nginx 的安全配置对于保护 Web 服务器免受各种攻击至关重要。合理的安全配置可以有效防止常见的安全威胁。基础安全配置:# 隐藏 Nginx 版本号server_tokens off;# 限制请求方法if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 405;}# 限制请求体大小client_max_body_size 10m;# 限制请求头大小client_header_buffer_size 1k;large_client_header_buffers 4 4k;# 超时设置client_body_timeout 10;client_header_timeout 10;keepalive_timeout 5 5;send_timeout 10;防止常见攻击:1. 防止 SQL 注入:location ~* \.(php|jsp|asp)$ { if ($args ~* "union.*select.*\(") { return 403; } if ($args ~* "concat.*\(") { return 403; }}2. 防止 XSS 攻击:location ~* \.(php|html|htm)$ { if ($args ~* "<script>|</script>|javascript:|onerror=|onload=|onclick=") { return 403; }}3. 防止文件包含攻击:location ~* \.(php|inc|config)$ { if ($args ~* "\.\./") { return 403; }}4. 防止目录遍历:location ~* /\.\. { deny all;}访问控制:# IP 白名单location /admin { allow 192.168.1.0/24; allow 10.0.0.0/8; deny all;}# IP 黑名单location / { deny 192.168.1.100; deny 192.168.1.101; allow all;}# 基本认证location /admin { auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/.htpasswd;}防止 DDoS 攻击:# 限制连接数limit_conn_zone $binary_remote_addr zone=conn_limit:10m;server { limit_conn conn_limit 10; # 限制请求速率 limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s; limit_req zone=req_limit burst=20 nodelay; # 限制带宽 limit_rate_after 10m; limit_rate 1m;}SSL/TLS 安全配置:server { listen 443 ssl http2; server_name example.com; # 证书配置 ssl_certificate /etc/nginx/ssl/example.com.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key; # SSL 协议 ssl_protocols TLSv1.2 TLSv1.3; # 加密套件 ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384; ssl_prefer_server_ciphers on; # SSL 会话缓存 ssl_session_cache shared:SSL:50m; ssl_session_timeout 1d; ssl_session_tickets off; # OCSP Stapling ssl_stapling on; ssl_stapling_verify on; ssl_trusted_certificate /etc/nginx/ssl/chain.crt; # HSTS add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; # 其他安全头 add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';" always;}文件安全:# 禁止访问隐藏文件location ~ /\. { deny all; access_log off; log_not_found off;}# 禁止访问敏感文件location ~* \.(htaccess|htpasswd|ini|log|sh|sql|bak|old|swp|tmp)$ { deny all; access_log off; log_not_found off;}# 禁止访问备份文件location ~* \~$ { deny all; access_log off; log_not_found off;}# 禁止目录浏览autoindex off;# 禁止访问特定目录location ~* ^/(admin|config|backup|tmp)/ { deny all;}防止恶意 User-Agent:# 阻止恶意爬虫if ($http_user_agent ~* (bot|crawl|spider|scraper)) { return 403;}# 阻止特定 User-Agentif ($http_user_agent ~* (wget|curl|python-requests)) { return 403;}防止图片盗链:location ~* \.(jpg|jpeg|png|gif|ico|svg)$ { valid_referers none blocked example.com *.example.com; if ($invalid_referer) { return 403; }}日志安全:# 自定义日志格式,记录更多安全信息log_format security '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' '$request_time $upstream_response_time ' '$http_x_forwarded_for';# 访问日志access_log /var/log/nginx/access.log security;# 错误日志error_log /var/log/nginx/error.log warn;# 敏感路径不记录日志location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2)$ { access_log off;}防止缓冲区溢出:# 限制缓冲区大小client_body_buffer_size 128k;client_header_buffer_size 1k;large_client_header_buffers 4 4k;client_max_body_size 10m;# 代理缓冲区proxy_buffer_size 4k;proxy_buffers 8 4k;proxy_busy_buffers_size 8k;安全最佳实践:定期更新:保持 Nginx 和系统补丁最新最小权限原则:使用非 root 用户运行 Nginx禁用不必要的模块:减少攻击面配置防火墙:限制不必要的端口访问使用 HTTPS:启用 SSL/TLS 加密定期审计日志:监控异常访问实施 WAF:使用 Web 应用防火墙备份配置:定期备份配置文件测试配置:使用 nginx -t 测试配置监控性能:使用监控工具跟踪性能指标完整安全配置示例:user nginx;worker_processes auto;worker_rlimit_nofile 65535;# 隐藏版本号server_tokens off;events { worker_connections 1024; use epoll;}http { # 基础安全 client_max_body_size 10m; client_header_buffer_size 1k; large_client_header_buffers 4 4k; # 超时设置 client_body_timeout 10; client_header_timeout 10; keepalive_timeout 5 5; send_timeout 10; # 限流 limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s; limit_conn_zone $binary_remote_addr zone=conn_limit:10m; # 日志 log_format security '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"'; access_log /var/log/nginx/access.log security; error_log /var/log/nginx/error.log warn; # Gzip gzip on; gzip_vary on; gzip_min_length 1024; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript; server { listen 80; server_name example.com; # 重定向到 HTTPS return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name example.com; # SSL 配置 ssl_certificate /etc/nginx/ssl/example.com.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256; ssl_prefer_server_ciphers on; ssl_session_cache shared:SSL:50m; ssl_session_timeout 1d; # 安全头 add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; # 限流 limit_req zone=req_limit burst=20 nodelay; limit_conn conn_limit 10; # 禁止访问隐藏文件 location ~ /\. { deny all; access_log off; } # 禁止访问敏感文件 location ~* \.(htaccess|htpasswd|ini|log|sh|sql|bak|old|swp|tmp)$ { deny all; access_log off; } # 管理后台访问控制 location /admin { allow 192.168.1.0/24; deny all; auth_basic "Restricted"; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass http://backend; } # 主站点 location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }}
阅读 0·2月21日 16:57

Nginx 如何实现限流?有哪些限流策略?

Nginx 如何实现限流?有哪些限流策略?Nginx 提供了强大的限流功能,可以有效防止 DDoS 攻击、保护服务器资源、防止恶意请求。Nginx 的限流主要通过 limit_req 和 limit_conn 模块实现。请求速率限制(limit_req):http { # 定义限流区域,基于客户端 IP limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s; # 定义限流区域,基于请求 URI limit_req_zone $request_uri zone=uri:10m rate=5r/s; # 定义限流区域,基于服务器名称 limit_req_zone $server_name zone=server:10m rate=100r/s; server { listen 80; server_name example.com; # 应用限流 location / { limit_req zone=one burst=20 nodelay; proxy_pass http://backend; } # API 接口限流 location /api/ { limit_req zone=one burst=10 nodelay; limit_req_status 429; proxy_pass http://api_backend; } }}参数说明:limitreqzone:定义限流区域$binary_remote_addr:客户端 IP 地址(二进制格式,节省内存)zone=one:10m:区域名称和共享内存大小(10M 可存储约 16 万个 IP)rate=10r/s:每秒允许 10 个请求limit_req:应用限流规则zone=one:使用的限流区域burst=20:允许的突发请求数nodelay:不延迟处理突发请求limitreqstatus:超过限制时返回的状态码(默认 503)连接数限制(limit_conn):http { # 定义连接数限制区域 limit_conn_zone $binary_remote_addr zone=addr:10m; # 定义服务器连接数限制区域 limit_conn_zone $server_name zone=server:10m; server { listen 80; server_name example.com; # 限制每个 IP 的并发连接数 limit_conn addr 10; # 限制服务器的总连接数 limit_conn server 1000; location / { proxy_pass http://backend; } }}带宽限制:server { listen 80; server_name example.com; location /download/ { # 限制下载速度为 1MB/s limit_rate 1m; # 前 10MB 不限速 limit_rate_after 10m; root /var/www/files; }}综合限流配置:http { # 请求速率限制 limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s; limit_req_zone $request_uri zone=uri_limit:10m rate=5r/s; # 连接数限制 limit_conn_zone $binary_remote_addr zone=conn_limit:10m; # 状态码限制 limit_req_status 429; limit_conn_status 429; server { listen 80; server_name example.com; # 全局限流 limit_conn conn_limit 10; # 首页限流 location = / { limit_req zone=req_limit burst=20 nodelay; proxy_pass http://backend; } # API 接口严格限流 location /api/ { limit_req zone=req_limit burst=5 nodelay; limit_req zone=uri_limit burst=2 nodelay; proxy_pass http://api_backend; } # 下载限速 location /download/ { limit_rate 1m; limit_rate_after 10m; root /var/www/files; } # 静态资源不限流 location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2)$ { root /var/www/static; } }}白名单配置:http { # 定义限流区域 limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s; # 定义白名单 geo $limit_key { default $binary_remote_addr; 192.168.1.0/24 ""; 10.0.0.0/8 ""; } # 基于白名单的限流 limit_req_zone $limit_key zone=whitelist_limit:10m rate=10r/s; server { listen 80; server_name example.com; location / { limit_req zone=whitelist_limit burst=20 nodelay; proxy_pass http://backend; } }}动态限流:http { # 根据请求方法限流 map $request_method $limit_key { default $binary_remote_addr; GET ""; HEAD ""; } limit_req_zone $limit_key zone=dynamic_limit:10m rate=10r/s; server { listen 80; server_name example.com; location / { limit_req zone=dynamic_limit burst=20 nodelay; proxy_pass http://backend; } }}限流日志:http { # 自定义日志格式,包含限流信息 log_format limit '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' 'rt=$request_time limit=$limit_req_status'; access_log /var/log/nginx/access.log limit; # 限流区域 limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s; server { listen 80; server_name example.com; location / { limit_req zone=req_limit burst=20 nodelay; limit_req_log_level warn; proxy_pass http://backend; } }}限流策略选择:固定窗口限流:rate=10r/s,每秒固定请求数滑动窗口限流:通过 burst 参数实现令牌桶算法:Nginx 默认使用,允许突发流量漏桶算法:通过 nodelay 参数控制实际应用场景:1. API 接口限流:limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/min;location /api/ { limit_req zone=api_limit burst=10 nodelay; limit_req_status 429; add_header X-RateLimit-Limit "100"; add_header X-RateLimit-Remaining "90"; add_header X-RateLimit-Reset "60"; proxy_pass http://api_backend;}2. 登录接口限流:limit_req_zone $binary_remote_addr zone=login_limit:10m rate=5r/min;location /login { limit_req zone=login_limit burst=2 nodelay; limit_req_status 429; proxy_pass http://auth_backend;}3. 文件下载限速:location /download/ { limit_rate 500k; limit_rate_after 5m; root /var/www/files;}4. 防止暴力破解:limit_req_zone $binary_remote_addr zone=auth_limit:10m rate=3r/min;location ~* ^/(login|register|reset-password) { limit_req zone=auth_limit burst=1 nodelay; limit_req_status 429; proxy_pass http://auth_backend;}监控和调试:# 启用限流状态监控location /limit_status { limit_req_status 429; add_header Content-Type text/plain; return 200 "Rate limit status: $limit_req_status";}# 查看限流统计location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all;}最佳实践:合理设置速率:根据业务需求设置合理的限流速率使用 burst:允许一定程度的突发流量返回友好错误:设置 429 状态码,返回友好提示白名单机制:对可信 IP 放开限流监控限流效果:定期检查限流日志,调整策略分层限流:对不同接口设置不同的限流策略结合缓存:对静态资源使用缓存,减少限流压力性能考虑:共享内存大小:根据 IP 数量合理设置 zone 大小限流粒度:选择合适的限流键(IP、URI 等)日志级别:生产环境使用 warn 级别,减少日志量nodelay 使用:根据场景选择是否使用 nodelay
阅读 0·2月21日 16:57

Nginx 如何实现访问控制?有哪些访问控制方法?

Nginx 如何实现访问控制?有哪些访问控制方法?Nginx 提供了多种访问控制方法,包括基于 IP 的访问控制、基本认证、访问令牌等,可以有效保护敏感资源。IP 访问控制:server { listen 80; server_name example.com; # IP 白名单 location /admin { allow 192.168.1.0/24; allow 10.0.0.0/8; deny all; proxy_pass http://backend; } # IP 黑名单 location / { deny 192.168.1.100; deny 192.168.1.101; allow all; proxy_pass http://backend; }}基本认证:server { listen 80; server_name example.com; # 创建密码文件 # htpasswd -c /etc/nginx/.htpasswd username location /admin { auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass http://backend; } # 多用户认证 location /api { auth_basic "API Access"; auth_basic_user_file /etc/nginx/.htpasswd_api; proxy_pass http://api_backend; }}访问令牌:server { listen 80; server_name example.com; # 基于 Header 的访问控制 location /api { if ($http_authorization !~* "Bearer .*") { return 401; } proxy_pass http://api_backend; } # 基于查询参数的访问控制 location /protected { if ($arg_token != "secret_token") { return 403; } proxy_pass http://backend; }}地理位置访问控制:http { # 定义地理位置映射 geo $allowed_country { default no; CN yes; US yes; } server { listen 80; server_name example.com; location / { if ($allowed_country = no) { return 403; } proxy_pass http://backend; } }}基于请求方法的访问控制:server { listen 80; server_name example.com; # 限制允许的请求方法 if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 405; } # 特定路径只允许特定方法 location /api { if ($request_method !~ ^(GET|POST)$ ) { return 405; } proxy_pass http://api_backend; } # 只读接口 location /api/read { if ($request_method !~ ^(GET|HEAD)$ ) { return 405; } proxy_pass http://api_backend; }}基于请求头的访问控制:server { listen 80; server_name example.com; # 检查特定的请求头 location /api { if ($http_x_api_key = "") { return 401; } proxy_pass http://api_backend; } # 检查 User-Agent location / { if ($http_user_agent ~* (bot|crawl|spider)) { return 403; } proxy_pass http://backend; } # 检查 Referer location /download { valid_referers none blocked example.com *.example.com; if ($invalid_referer) { return 403; } root /var/www/files; }}复杂访问控制:http { # 定义多个访问控制变量 geo $whitelist { default 0; 192.168.1.0/24 1; 10.0.0.0/8 1; } map $http_x_api_key $api_valid { default 0; "secret_key_123" 1; "secret_key_456" 1; } server { listen 80; server_name example.com; # 组合多个访问控制条件 location /admin { # IP 白名单 allow 192.168.1.0/24; allow 10.0.0.0/8; deny all; # 基本认证 auth_basic "Admin Area"; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass http://backend; } # API 访问控制 location /api { # 检查 API Key if ($api_valid = 0) { return 401; } # 限制请求方法 if ($request_method !~ ^(GET|POST|PUT|DELETE)$ ) { return 405; } proxy_pass http://api_backend; } # 静态资源访问控制 location /protected { # IP 白名单或认证 satisfy any; allow 192.168.1.0/24; deny all; auth_basic "Protected Area"; auth_basic_user_file /etc/nginx/.htpasswd; root /var/www/protected; } }}基于时间的访问控制:http { # 定义时间段 map $time_iso8601 $business_hours { default 0; ~^(\d{4}-\d{2}-\d{2}T(09|1[0-9]|2[0-1])) 1; } server { listen 80; server_name example.com; # 只在工作时间允许访问 location /admin { if ($business_hours = 0) { return 403; } proxy_pass http://backend; } }}防止目录遍历:server { listen 80; server_name example.com; # 禁止访问父目录 location ~* /\.\. { deny all; } # 禁止访问隐藏文件 location ~ /\. { deny all; access_log off; log_not_found off; } # 禁止目录浏览 autoindex off; location / { proxy_pass http://backend; }}限制文件类型访问:server { listen 80; server_name example.com; # 禁止访问敏感文件 location ~* \.(htaccess|htpasswd|ini|log|sh|sql|bak|old|swp|tmp)$ { deny all; access_log off; log_not_found off; } # 只允许特定文件类型 location /uploads { location ~* \.(jpg|jpeg|png|gif|pdf|doc|docx)$ { root /var/www/uploads; } location ~* \.(php|sh|exe|bat)$ { deny all; } }}访问控制最佳实践:最小权限原则:只授予必要的访问权限多层防护:组合使用多种访问控制方法定期审查:定期检查和更新访问控制规则日志记录:记录所有访问控制事件白名单优先:优先使用白名单而非黑名单测试配置:在生产环境前充分测试访问控制规则监控异常:监控异常访问行为及时更新:及时更新密码和访问令牌完整访问控制配置示例:http { # IP 白名单 geo $whitelist { default 0; 192.168.1.0/24 1; 10.0.0.0/8 1; } # API Key 验证 map $http_x_api_key $api_valid { default 0; "secret_key_123" 1; "secret_key_456" 1; } # 工作时间 map $time_iso8601 $business_hours { default 0; ~^(\d{4}-\d{2}-\d{2}T(09|1[0-9]|2[0-1])) 1; } server { listen 80; server_name example.com; # 管理后台 location /admin { # IP 白名单 allow 192.168.1.0/24; allow 10.0.0.0/8; deny all; # 基本认证 auth_basic "Admin Area"; auth_basic_user_file /etc/nginx/.htpasswd; # 工作时间限制 if ($business_hours = 0) { return 403; } proxy_pass http://backend; } # API 接口 location /api { # API Key 验证 if ($api_valid = 0) { return 401; } # 限制请求方法 if ($request_method !~ ^(GET|POST|PUT|DELETE)$ ) { return 405; } # 限流 limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/min; limit_req zone=api_limit burst=10 nodelay; proxy_pass http://api_backend; } # 受保护资源 location /protected { # IP 白名单或认证 satisfy any; allow 192.168.1.0/24; deny all; auth_basic "Protected Area"; auth_basic_user_file /etc/nginx/.htpasswd; root /var/www/protected; } # 禁止访问敏感文件 location ~* \.(htaccess|htpasswd|ini|log|sh|sql|bak|old|swp|tmp)$ { deny all; access_log off; log_not_found off; } # 禁止目录遍历 location ~* /\.\. { deny all; } # 禁止访问隐藏文件 location ~ /\. { deny all; access_log off; log_not_found off; } # 主站点 location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }}
阅读 0·2月21日 16:57

Nginx 如何实现缓存?如何配置缓存策略?

Nginx 如何实现缓存?如何配置缓存策略?Nginx 提供了强大的缓存功能,可以缓存后端服务器的响应,减轻后端负载,提高响应速度。Nginx 支持代理缓存和 FastCGI 缓存等多种缓存方式。代理缓存配置:http { # 定义缓存路径和参数 proxy_cache_path /var/cache/nginx/proxy levels=1:2 keys_zone=proxy_cache:10m max_size=1g inactive=60m use_temp_path=off; server { listen 80; server_name example.com; location / { proxy_cache proxy_cache; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; proxy_cache_key "$scheme$request_method$host$request_uri"; proxy_cache_bypass $http_cache_control; add_header X-Cache-Status $upstream_cache_status; proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }}缓存参数说明:proxycachepath:定义缓存存储路径和参数levels:缓存目录层级结构keys_zone:共享内存区域名称和大小max_size:缓存最大大小inactive:缓存项不活动时间use_temp_path:是否使用临时路径proxy_cache:指定使用的缓存区域proxycachevalid:设置不同状态码的缓存时间200 302 10m:200 和 302 状态码缓存 10 分钟404 1m:404 状态码缓存 1 分钟proxycachekey:定义缓存键proxycachebypass:绕过缓存的条件FastCGI 缓存配置:http { fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=fastcgi_cache:10m max_size=1g inactive=60m; server { listen 80; server_name example.com; location ~ \.php$ { fastcgi_cache fastcgi_cache; fastcgi_cache_valid 200 60m; fastcgi_cache_methods GET HEAD; fastcgi_cache_bypass $skip_cache; fastcgi_no_cache $skip_cache; add_header X-Cache-Status $upstream_cache_status; fastcgi_pass unix:/var/run/php/php8.0-fpm.sock; fastcgi_index index.php; include fastcgi_params; } }}缓存清除:Nginx 开源版本不支持主动缓存清除,可以通过以下方式实现:设置缓存过期时间:通过 proxy_cache_valid 控制使用第三方模块:如 ngxcachepurge手动删除缓存文件:根据缓存键删除对应文件缓存策略配置:# 根据请求方法缓存proxy_cache_methods GET HEAD;# 根据响应头缓存proxy_ignore_headers X-Accel-Expires Expires Cache-Control Set-Cookie;# 缓存最小请求次数proxy_cache_min_uses 2;# 缓存锁定,防止缓存风暴proxy_cache_lock on;proxy_cache_lock_timeout 5s;# 缓存背景更新proxy_cache_background_update on;proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;动态缓存控制:# 根据条件决定是否缓存map $request_uri $skip_cache { default 0; ~*/admin/ 1; ~*/api/ 1;}# 根据响应头决定是否缓存map $upstream_http_cache_control $skip_cache { ~*no-cache 1; ~*private 1; default 0;}静态文件缓存:location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$ { expires 1y; add_header Cache-Control "public, immutable"; access_log off;}缓存状态监控:add_header X-Cache-Status $upstream_cache_status;# 缓存状态值:# MISS - 未命中缓存# BYPASS - 绕过缓存# EXPIRED - 缓存过期# STALE - 使用过期缓存# UPDATING - 缓存更新中# HIT - 命中缓存缓存优化建议:合理设置缓存时间,平衡新鲜度和性能使用缓存键包含必要参数,避免缓存冲突对动态内容禁用缓存定期清理过期缓存监控缓存命中率,调整缓存策略使用缓存锁定防止缓存风暴对静态资源使用浏览器缓存完整配置示例:http { # 代理缓存 proxy_cache_path /var/cache/nginx/proxy levels=1:2 keys_zone=proxy_cache:100m max_size=10g inactive=60m use_temp_path=off; # FastCGI 缓存 fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=fastcgi_cache:100m max_size=10g inactive=60m; # 缓存跳过条件 map $request_uri $skip_cache { default 0; ~*/admin/ 1; ~*/api/ 1; ~*/user/ 1; } server { listen 80; server_name example.com; # 静态文件 location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2)$ { expires 1y; add_header Cache-Control "public, immutable"; } # 动态内容代理 location / { proxy_cache proxy_cache; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; proxy_cache_key "$scheme$request_method$host$request_uri"; proxy_cache_bypass $skip_cache; proxy_no_cache $skip_cache; add_header X-Cache-Status $upstream_cache_status; proxy_pass http://backend; } # PHP 文件 location ~ \.php$ { fastcgi_cache fastcgi_cache; fastcgi_cache_valid 200 60m; fastcgi_cache_bypass $skip_cache; fastcgi_no_cache $skip_cache; add_header X-Cache-Status $upstream_cache_status; fastcgi_pass unix:/var/run/php/php8.0-fpm.sock; } }}
阅读 0·2月21日 16:57

如何在 Monorepo 项目中配置和使用 Prettier?

Prettier 在 Monorepo 项目中的应用Monorepo 项目中统一管理多个包的代码格式是一个重要挑战,Prettier 提供了多种解决方案来确保整个 monorepo 的代码风格一致。Monorepo 配置策略1. 根目录统一配置在 monorepo 根目录创建 .prettierrc:{ "semi": true, "singleQuote": true, "tabWidth": 2, "trailingComma": "es5"}2. 共享配置包创建独立的配置包 @my-org/prettier-config:// packages/prettier-config/index.jsmodule.exports = { semi: true, singleQuote: true, tabWidth: 2, trailingComma: "es5", printWidth: 80,};在各个包中使用:{ "prettier": "@my-org/prettier-config"}不同包的差异化配置使用 overrides 为不同包设置不同规则:{ "semi": true, "overrides": [ { "files": "packages/ui/**/*", "options": { "printWidth": 100 } }, { "files": "packages/server/**/*", "options": { "printWidth": 80 } } ]}工具集成1. Turborepo 集成在 turbo.json 中配置:{ "pipeline": { "format": { "outputs": [] } }}在 package.json 中添加脚本:{ "scripts": { "format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,css,md}\"", "format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,css,md}\"" }}2. Nx 集成Nx 提供了专门的 Prettier 支持:{ "targets": { "format": { "executor": "@nx/vite:format", "options": { "write": true } } }}3. Lerna 集成使用 Lerna 的 --scope 选项格式化特定包:lerna exec --scope @my-org/ui -- prettier --write "**/*.js"性能优化1. 增量格式化# 只格式化修改的文件git diff --name-only --diff-filter=ACM | grep '\.js$' | xargs prettier --write2. 并行处理# 使用 GNU parallel 并行格式化find . -name "*.js" | parallel prettier --write3. 缓存机制# 使用 Prettier 缓存prettier --write --cache "**/*.js"CI/CD 集成GitHub Actions 配置:name: Format Checkon: [push, pull_request]jobs: format: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '18' - run: npm ci - run: npm run format:check最佳实践1. 配置管理在根目录维护统一的 Prettier 配置使用共享配置包确保一致性定期同步各包的配置2. 依赖管理在根目录安装 Prettier锁定 Prettier 版本使用 workspace 协议管理依赖3. 团队协作在文档中说明 monorepo 的格式化策略提供统一的编辑器配置在 CI 中强制检查格式4. 性能考虑使用缓存提高格式化速度合理配置 .prettierignore只格式化必要的文件通过合理配置,Prettier 可以在 monorepo 项目中有效统一代码风格,提高开发效率。
阅读 0·2月21日 16:56

如何在 CI/CD 流程中集成 Prettier 进行代码格式检查?

Prettier 在 CI/CD 中的集成实践将 Prettier 集成到 CI/CD 流程中可以确保所有提交的代码都符合统一的格式规范,提高代码质量和团队协作效率。Git Hooks 集成使用 Husky 和 lint-staged 在 Git 提交前自动格式化代码:安装依赖 npm install --save-dev husky lint-staged prettier npx husky install npm pkg set scripts.prepare="husky install"配置 lint-staged在 package.json 中添加: { "lint-staged": { "*.{js,jsx,ts,tsx,json,css,scss,md}": [ "prettier --write" ] } }创建 Git Hook npx husky add .husky/pre-commit "npx lint-staged"CI/CD 配置GitHub Actions创建 .github/workflows/prettier.yml:name: Prettier Checkon: [push, pull_request]jobs: prettier: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '18' - run: npm install - run: npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,scss,md}"GitLab CI在 .gitlab-ci.yml 中添加:prettier: stage: test script: - npm install - npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,scss,md}" only: - merge_requests - main常用命令格式化文件: npx prettier --write "src/**/*.js"检查格式: npx prettier --check "src/**/*.js"格式化所有文件: npx prettier --write .查看差异: npx prettier --list-different "src/**/*.js"最佳实践团队统一配置: 确保所有开发者使用相同的 Prettier 配置自动化检查: 在 CI/CD 中强制检查代码格式自动修复: 使用 --write 选项自动修复格式问题忽略文件: 合理配置 .prettierignore 避免不必要的格式化版本锁定: 锁定 Prettier 版本确保一致性通过在 CI/CD 中集成 Prettier,可以确保代码库始终保持统一的格式规范,减少代码审查时的格式争议。
阅读 0·2月21日 16:56

Prettier 命令行工具有哪些常用命令和选项?

Prettier 命令行工具详解Prettier 提供了丰富的命令行工具,可以灵活地进行代码格式化、检查和配置管理。基本命令1. 格式化文件# 格式化单个文件prettier --write index.js# 格式化多个文件prettier --write src/**/*.js# 格式化所有支持的文件prettier --write .2. 检查文件格式# 检查文件格式是否正确prettier --check index.js# 检查多个文件prettier --check "src/**/*.{js,jsx,ts,tsx}"# 检查所有文件prettier --check .3. 查看格式化差异# 显示格式化后的差异prettier --diff index.js# 列出需要格式化的文件prettier --list-different "src/**/*.js"常用选项1. 配置相关# 指定配置文件prettier --config .prettierrc.custom --write index.js# 指定忽略文件prettier --ignore-path .prettierignore.custom --write .# 禁用默认忽略prettier --write --ignore-unknown index.js2. 输出控制# 输出到标准输出(不修改文件)prettier index.js# 指定输出目录prettier --out-dir formatted src/**/*.js# 使用缓存prettier --write --cache "src/**/*.js"# 清除缓存prettier --write --cache --cache-strategy content "src/**/*.js"3. 调试相关# 显示调试信息prettier --debug-check index.js# 显示使用的配置prettier --find-config-path index.js# 显示解析器信息prettier --help高级用法1. 与其他工具结合# 与 find 结合使用find src -name "*.js" | xargs prettier --write# 与 git 结合使用git diff --name-only --diff-filter=ACM | grep '\.js$' | xargs prettier --write2. 格式化特定文件类型# 只格式化 JavaScript 文件prettier --write "**/*.js"# 格式化多种文件类型prettier --write "**/*.{js,jsx,ts,tsx,json,css,md}"3. 使用 npx 运行# 使用 npx 运行(无需全局安装)npx prettier --write index.js# 指定版本运行npx prettier@2.8.0 --write index.js实用脚本在 package.json 中添加常用脚本:{ "scripts": { "format": "prettier --write \"src/**/*.{js,jsx,ts,tsx,json,css,md}\"", "format:check": "prettier --check \"src/**/*.{js,jsx,ts,tsx,json,css,md}\"", "format:staged": "lint-staged", "format:all": "prettier --write ." }}常见问题解决1. 文件编码问题# 指定文件编码prettier --write --encoding utf-8 index.js2. 权限问题# 使用 sudo 运行(不推荐)sudo prettier --write index.js3. 性能问题# 使用缓存提高性能prettier --write --cache "**/*.js"掌握 Prettier 命令行工具可以更高效地进行代码格式化管理。
阅读 0·2月21日 16:56

Prettier 与其他代码格式化工具有什么区别?如何选择?

Prettier 与其他代码格式化工具的对比代码格式化工具市场上有多种选择,了解 Prettier 与其他工具的对比有助于选择最适合项目的工具。主要格式化工具对比1. Prettier vs ESLint| 特性 | Prettier | ESLint ||------|----------|--------|| 主要功能 | 代码格式化 | 代码质量检查 || 配置复杂度 | 低(有限选项) | 高(大量规则) || 可扩展性 | 中等 | 高 || 性能 | 快 | 较慢 || 学习曲线 | 低 | 高 |选择建议: 两者结合使用,Prettier 负责格式化,ESLint 负责质量检查。2. Prettier vs Standard.js| 特性 | Prettier | Standard.js ||------|----------|-------------|| 配置灵活性 | 中等 | 低(固定风格) || 零配置 | 支持 | 支持 || 社区活跃度 | 高 | 中等 || 可定制性 | 中等 | 低 |选择建议: Standard.js 适合追求极致零配置的团队,Prettier 适合需要一定灵活性的团队。3. Prettier vs Beautify| 特性 | Prettier | Beautify ||------|----------|----------|| 确定性 | 高 | 低 || AST 解析 | 是 | 否 || 语言支持 | 广泛 | 有限 || 配置选项 | 有限 | 丰富 |选择建议: Prettier 更适合团队协作,Beautify 更适合个人使用。4. Prettier vs Black (Python)| 特性 | Prettier | Black ||------|----------|-------|| 目标语言 | 多语言 | Python || 设计理念 | 代码格式化 | 代码格式化 || 配置选项 | 有限 | 极少 || 社区支持 | 广泛 | Python 社区 |选择建议: Python 项目使用 Black,其他语言使用 Prettier。Prettier 的优势1. 确定性输出相同输入总是产生相同输出避免格式化争议适合团队协作2. 广泛的语言支持支持 JavaScript、TypeScript、CSS、HTML 等通过插件支持更多语言一站式格式化解决方案3. 零配置开箱即用提供合理的默认配置减少配置时间快速上手4. 强大的编辑器集成VS Code、WebStorm 等主流编辑器支持保存时自动格式化实时预览格式化效果Prettier 的局限性1. 配置选项有限无法满足所有个性化需求某些格式无法调整可能与团队习惯不符2. 性能问题大项目中格式化速度较慢内存占用较高需要优化策略3. 版本兼容性不同版本格式化结果可能不同升级需要谨慎团队版本统一困难选择建议使用 Prettier 的场景:多语言项目需要团队协作追求代码风格统一希望零配置快速上手考虑其他工具的场景:单一语言项目(如 Python 使用 Black)需要高度定制化个人项目特定框架的格式化需求最佳实践1. 工具组合Prettier + ESLint: 格式化 + 质量检查Prettier + Stylelint: CSS 格式化 + 检查Prettier + Husky: 自动化工作流2. 团队决策评估团队需求考虑项目特点进行工具试用制定使用规范3. 持续优化定期评估工具效果收集团队反馈调整配置策略关注工具更新通过合理选择和组合代码格式化工具,可以显著提高开发效率和代码质量。
阅读 0·2月21日 16:56