Otimização de Desempenho
Otimização de Desempenho do XOOPS
Seção intitulada “Otimização de Desempenho do XOOPS”Guia abrangente para otimizar XOOPS para máxima velocidade e eficiência.
Visão Geral da Otimização de Desempenho
Seção intitulada “Visão Geral da Otimização de Desempenho”graph TD A[Desempenho] --> B[Cache] A --> C[Banco de Dados] A --> D[Servidor Web] A --> E[Frontend] A --> F[Código] B --> B1[Cache de Página] B --> B2[Cache de Consulta] B --> B3[Cache de Template] C --> C1[Índices] C --> C2[Consultas] C --> C3[Otimização] D --> D1[Compressão] D --> D2[Headers] D --> D3[Conexão] E --> E1[Imagens] E --> E2[CSS/JS] E --> E3[Lazy Load] F --> F1[Módulos] F --> F2[Consultas]Configuração de Cache
Seção intitulada “Configuração de Cache”O cache é a forma mais rápida de melhorar o desempenho.
Cache no Nível de Página
Seção intitulada “Cache no Nível de Página”Habilite cache de página completa em XOOPS:
Painel de Administração > Sistema > Preferências > Configurações de Cache
Habilitar Cache: SimTipo de Cache: Cache de Arquivo (ou APCu/Memcache)Tempo de Vida do Cache: 3600 segundos (1 hora)Cache de Listas de Módulo: SimCache de Configuração: SimCache de Resultados de Busca: SimCache Baseado em Arquivo
Seção intitulada “Cache Baseado em Arquivo”Configure a localização do cache do arquivo:
# Criar diretório de cache fora da raiz web (mais seguro)mkdir -p /var/cache/xoopschown www-data:www-data /var/cache/xoopschmod 755 /var/cache/xoops
# Editar mainfile.phpdefine('XOOPS_CACHE_PATH', '/var/cache/xoops/');APCu Caching
Seção intitulada “APCu Caching”APCu provides in-memory caching (very fast):
# Install APCuapt-get install php-apcu
# Verify installationphp -m | grep apcu
# Configure in php.iniapc.enabled = 1apc.memory_size = 128Mapc.ttl = 0apc.user_ttl = 3600apc.shm_size = 128Enable in XOOPS:
Admin Panel > System > Preferences > Cache Settings
Cache Type: APCuMemcache/Redis Caching
Seção intitulada “Memcache/Redis Caching”Distributed caching for high-traffic sites:
Install Memcache:
# Install Memcache serverapt-get install memcached
# Start servicesystemctl start memcachedsystemctl enable memcached
# Verify runningnetstat -tlnp | grep memcached# Should show listening on port 11211Configure in XOOPS:
Edit mainfile.php:
// Memcache configurationdefine('XOOPS_CACHE_TYPE', 'memcache');define('XOOPS_CACHE_HOST', 'localhost');define('XOOPS_CACHE_PORT', 11211);define('XOOPS_CACHE_TIMEOUT', 0);Or in admin panel:
Cache Type: MemcacheMemcache Host: localhost:11211Template Caching
Seção intitulada “Template Caching”Compile and cache XOOPS templates:
# Ensure templates_c is writablechmod 777 /var/www/html/xoops/templates_c/
# Clear old cached templatesrm -rf /var/www/html/xoops/templates_c/*Configure in theme:
<!-- In theme xoops_version.php -->{smarty.const.XOOPS_VAR_PATH|constant}<{$xoops_meta}>
<!-- Templates use caching -->{cache} [Cached content here]{/cache}Database Optimization
Seção intitulada “Database Optimization”Add Database Indexes
Seção intitulada “Add Database Indexes”Properly indexed databases query much faster.
-- Check current indexesSHOW INDEXES FROM xoops_users;
-- Common indexes to addALTER TABLE xoops_users ADD INDEX idx_uname (uname);ALTER TABLE xoops_users ADD INDEX idx_email (email);ALTER TABLE xoops_users ADD INDEX idx_uid_active (uid, user_actkey);
-- Add indexes to posts/content tablesALTER TABLE xoops_posts ADD INDEX idx_post_published (post_published);ALTER TABLE xoops_posts ADD INDEX idx_post_uid (post_uid);ALTER TABLE xoops_posts ADD INDEX idx_post_created (post_created);
-- Verify indexes createdSHOW INDEXES FROM xoops_users\GOptimize Tables
Seção intitulada “Optimize Tables”Regular table optimization improves performance:
-- Optimize all tablesOPTIMIZE TABLE xoops_users;OPTIMIZE TABLE xoops_posts;OPTIMIZE TABLE xoops_config;OPTIMIZE TABLE xoops_comments;
-- Or optimize all at onceREPAIR TABLE xoops_users;OPTIMIZE TABLE xoops_users;REPAIR TABLE xoops_posts;OPTIMIZE TABLE xoops_posts;Create automated optimization script:
#!/bin/bash# Database optimization script
echo "Optimizing XOOPS database..."
mysql -u xoops_user -p xoops_db << EOF-- Optimize all tablesOPTIMIZE TABLE xoops_users;OPTIMIZE TABLE xoops_posts;OPTIMIZE TABLE xoops_config;OPTIMIZE TABLE xoops_comments;OPTIMIZE TABLE xoops_users_online;
-- Show database sizeSELECT table_schema, ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) as total_mbFROM information_schema.tablesWHERE table_schema = 'xoops_db'GROUP BY table_schema;EOF
echo "Database optimization completed!"Schedule with cron:
# Weekly optimizationcrontab -e# Add: 0 3 * * 0 /usr/local/bin/optimize-xoops-db.shQuery Optimization
Seção intitulada “Query Optimization”Review slow queries:
-- Enable slow query logSET GLOBAL slow_query_log = 'ON';SET GLOBAL long_query_time = 2;
-- View slow queriesSELECT * FROM mysql.slow_log;
-- Or check slow log filetail -100 /var/log/mysql/slow.logCommon optimization techniques:
// SLOW - Avoid unnecessary queries in loopsforeach ($users as $user) { $profile = getUserProfile($user['uid']); // Query in loop! echo $profile['name'];}
// FAST - Get all data at once$profiles = getAllUserProfiles($user_ids);foreach ($users as $user) { echo $profiles[$user['uid']]['name'];}Increase Buffer Pool
Seção intitulada “Increase Buffer Pool”Configure MySQL for better caching:
Edit /etc/mysql/mysql.conf.d/mysqld.cnf:
# InnoDB Buffer Pool (50-80% of system RAM)innodb_buffer_pool_size = 1G
# Query Cache (optional, can be disabled in MySQL 5.7+)query_cache_size = 64Mquery_cache_type = 1
# Max Connectionsmax_connections = 500
# Max Allowed Packetmax_allowed_packet = 256M
# Connection timeoutconnect_timeout = 10Restart MySQL:
systemctl restart mysqlWeb Server Optimization
Seção intitulada “Web Server Optimization”Enable Gzip Compression
Seção intitulada “Enable Gzip Compression”Compress responses to reduce bandwidth:
Apache Configuration:
<IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
# Don't compress images and already compressed files SetEnvIfNoCase Request_URI \.(jpg|jpeg|png|gif|zip|gzip)$ no-gzip dont-vary
# Log compressed responses DeflateBufferSize 8096</IfModule>Nginx Configuration:
gzip on;gzip_types text/html text/plain text/css text/javascript application/javascript application/json;gzip_min_length 1000;gzip_vary on;gzip_comp_level 6;
# Don't compress already compressed formatsgzip_disable "msie6";Verify compression:
# Check if response is gzippedcurl -I -H "Accept-Encoding: gzip" http://your-domain.com/xoops/
# Should show:# Content-Encoding: gzipBrowser Caching Headers
Seção intitulada “Browser Caching Headers”Set cache expiration for static assets:
Apache:
<IfModule mod_expires.c> ExpiresActive On
# Cache images for 30 days ExpiresByType image/jpeg "access plus 30 days" ExpiresByType image/gif "access plus 30 days" ExpiresByType image/png "access plus 30 days" ExpiresByType image/svg+xml "access plus 30 days"
# Cache CSS/JS for 30 days ExpiresByType text/css "access plus 30 days" ExpiresByType application/javascript "access plus 30 days" ExpiresByType text/javascript "access plus 30 days"
# Cache fonts for 1 year ExpiresByType font/eot "access plus 1 year" ExpiresByType font/ttf "access plus 1 year" ExpiresByType font/woff "access plus 1 year" ExpiresByType font/woff2 "access plus 1 year"
# Don't cache HTML ExpiresByType text/html "access plus 1 hour"</IfModule>Nginx:
location ~* \.(jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$ { expires 30d; add_header Cache-Control "public, immutable";}
location ~* \.(css|js)$ { expires 30d; add_header Cache-Control "public";}
location ~ \.html$ { expires 1h; add_header Cache-Control "public";}Connection Keep-Alive
Seção intitulada “Connection Keep-Alive”Enable persistent HTTP connections:
Apache:
<IfModule mod_http.c> KeepAlive On KeepAliveTimeout 15 MaxKeepAliveRequests 100</IfModule>Nginx:
keepalive_timeout 15s;keepalive_requests 100;Frontend Optimization
Seção intitulada “Frontend Optimization”Optimize Images
Seção intitulada “Optimize Images”Reduce image file sizes:
# Batch compress JPEG imagesfor img in *.jpg; do convert "$img" -quality 85 "optimized_$img"done
# Batch compress PNG imagesfor img in *.png; do optipng -o2 "$img"done
# Or use imagemin CLInpm install -g imagemin-cliimagemin images/ --out-dir=images-optimizedMinify CSS and JavaScript
Seção intitulada “Minify CSS and JavaScript”Reduce CSS/JS file sizes:
Using Node.js tools:
# Install minifiersnpm install -g uglify-js clean-css-cli
# Minify JavaScriptuglifyjs script.js -o script.min.js
# Minify CSScleancss style.css -o style.min.cssUsing online tools:
- CSS Minifier: https://cssminifier.com/
- JavaScript Minifier: https://www.minifycode.com/javascript-minifier/
Lazy Load Images
Seção intitulada “Lazy Load Images”Load images only when needed:
<!-- Add loading="lazy" attribute --><img src="image.jpg" alt="Description" loading="lazy">
<!-- Or use JavaScript library for older browsers --><img class="lazy" src="placeholder.jpg" data-src="image.jpg" alt="Description">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vanilla-lazyload/17.1.2/lazyload.min.js"></script><script> var lazyLoad = new LazyLoad({ elements_selector: ".lazy" });</script>Reduce Render-Blocking Resources
Seção intitulada “Reduce Render-Blocking Resources”Load CSS/JS strategically:
<!-- Load critical CSS inline --><style> /* Critical styles for above-the-fold */</style>
<!-- Defer non-critical CSS --><link rel="stylesheet" href="style.css" media="print" onload="this.media='all'">
<!-- Defer JavaScript --><script src="script.js" defer></script>
<!-- Or use async for non-critical scripts --><script src="analytics.js" async></script>CDN Integration
Seção intitulada “CDN Integration”Use a Content Delivery Network for faster global access.
Popular CDNs
Seção intitulada “Popular CDNs”| CDN | Cost | Features |
|---|---|---|
| Cloudflare | Free/Paid | DDoS, DNS, Cache, Analytics |
| AWS CloudFront | Paid | High performance, global |
| Bunny CDN | Affordable | Storage, video, cache |
| jsDelivr | Free | JavaScript libraries |
| cdnjs | Free | Popular libraries |
Cloudflare Setup
Seção intitulada “Cloudflare Setup”-
Sign up at https://www.cloudflare.com/
-
Add your domain
-
Update nameservers with Cloudflare’s
-
Enable caching options:
- Cache Level: Aggressive
- Caching on everything: On
- Browser Caching TTL: 1 month
-
In XOOPS, update your domain to use Cloudflare DNS
Configure CDN in XOOPS
Seção intitulada “Configure CDN in XOOPS”Update image URLs to CDN:
Edit theme template:
<!-- Original --><img src="{$xoops_url}/uploads/image.jpg" alt="">
<!-- With CDN --><img src="https://cdn.your-domain.com/uploads/image.jpg" alt="">Or set in PHP:
// In mainfile.php or configdefine('XOOPS_CDN_URL', 'https://cdn.your-domain.com');
// In template<img src="{$smarty.const.XOOPS_CDN_URL}/uploads/image.jpg" alt="">Performance Monitoring
Seção intitulada “Performance Monitoring”PageSpeed Insights Testing
Seção intitulada “PageSpeed Insights Testing”Test your site performance:
- Visit Google PageSpeed Insights: https://pagespeed.web.dev/
- Enter your XOOPS URL
- Review recommendations
- Implement suggested improvements
Server Performance Monitoring
Seção intitulada “Server Performance Monitoring”Monitor real-time server metrics:
# Install monitoring toolsapt-get install htop iotop nethogs
# Monitor CPU and memoryhtop
# Monitor disk I/Oiotop
# Monitor networknethogsPHP Performance Profiling
Seção intitulada “PHP Performance Profiling”Identify slow PHP code:
<?php// Use Xdebug for profilingxdebug_start_trace('profile');
// Your code here$result = someExpensiveFunction();
xdebug_stop_trace();?>MySQL Query Monitoring
Seção intitulada “MySQL Query Monitoring”Track slow queries:
# Enable query loggingmysql -u root -p
SET GLOBAL general_log = 'ON';SET GLOBAL log_output = 'FILE';SET GLOBAL general_log_file = '/var/log/mysql/query.log';
# Review slow queriestail -f /var/log/mysql/slow.log
# Analyze query with EXPLAINEXPLAIN SELECT * FROM xoops_users WHERE uid = 1\GPerformance Optimization Checklist
Seção intitulada “Performance Optimization Checklist”Implement these for best performance:
- Caching: Enable file/APCu/Memcache caching
- Database: Add indexes, optimize tables
- Compression: Enable Gzip compression
- Browser Cache: Set cache headers
- Images: Optimize and compress
- CSS/JS: Minify files
- Lazy Loading: Implement for images
- CDN: Use for static assets
- Keep-Alive: Enable persistent connections
- Modules: Disable unused modules
- Themes: Use lightweight, optimized themes
- Monitoring: Track performance metrics
- Regular Maintenance: Clear cache, optimize DB
Performance Optimization Script
Seção intitulada “Performance Optimization Script”Automated optimization:
#!/bin/bash# Performance optimization script
echo "=== XOOPS Performance Optimization ==="
# Clear cacheecho "Clearing cache..."rm -rf /var/www/html/xoops/cache/*rm -rf /var/www/html/xoops/templates_c/*
# Optimize databaseecho "Optimizing database..."mysql -u xoops_user -p xoops_db << EOFOPTIMIZE TABLE xoops_users;OPTIMIZE TABLE xoops_posts;OPTIMIZE TABLE xoops_config;OPTIMIZE TABLE xoops_comments;EOF
# Check file permissionsecho "Verifying file permissions..."find /var/www/html/xoops -type f -exec chmod 644 {} \;find /var/www/html/xoops -type d -exec chmod 755 {} \;chmod 777 /var/www/html/xoops/cachechmod 777 /var/www/html/xoops/templates_cchmod 777 /var/www/html/xoops/uploadschmod 777 /var/www/html/xoops/var
# Generate performance reportecho "Performance Optimization Complete!"echo ""echo "Next steps:"echo "1. Test site at https://pagespeed.web.dev/"echo "2. Monitor performance in admin panel"echo "3. Consider CDN for static assets"echo "4. Review slow queries in MySQL"Before and After Metrics
Seção intitulada “Before and After Metrics”Track improvements:
Before Optimization:- Page Load Time: 3.5 seconds- Database Queries: 45- Cache Hit Rate: 0%- Database Size: 250MB
After Optimization:- Page Load Time: 0.8 seconds (77% faster)- Database Queries: 8 (cached)- Cache Hit Rate: 85%- Database Size: 120MB (optimized)Próximos Passos
Seção intitulada “Próximos Passos”- Revisar configuração básica
- Garantir medidas de segurança
- Implementar cache
- Monitorar desempenho com ferramentas
- Ajustar com base em métricas
Tags: #performance #optimization #caching #database #cdn
Artigos Relacionados:
- ../../06-Publisher-Module/User-Guide/Basic-Configuration
- System-Settings
- Security-Configuration
- ../Installation/Server-Requirements