在 Ubuntu 上提升 ThinkPHP 的响应速度,可以从多个方面进行优化。以下是一些常见的优化方法:
OPcache 可以显著提高 PHP 脚本的执行速度。确保在 php.ini
文件中启用了 OPcache:
[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
PHP 7 及以上版本相比 PHP 5 有显著的性能提升。确保你使用的是最新版本的 PHP。
database.php
中配置持久连接。ThinkPHP 提供了多种缓存方式,包括文件缓存、Redis 缓存等。合理使用缓存可以显著提高响应速度。
// 使用文件缓存
Cache::set('key', 'value', 3600);
// 使用 Redis 缓存
$redis = new \think\cache\driver\Redis();
$redis->set('key', 'value', 3600);
Nginx:
server {
listen 80;
server_name example.com;
root /path/to/your/project;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
include fastcgi.conf;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
Apache:
<VirtualHost *:80>
ServerName example.com
DocumentRoot /path/to/your/project
<Directory /path/to/your/project>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
<FilesMatch \.php$>
SetHandler "proxy:unix:/var/run/php/php7.4-fpm.sock|fcgi://localhost"
</FilesMatch>
</VirtualHost>
对于静态资源(如图片、CSS、JS 文件),使用 CDN 可以显著提高加载速度。
使用工具如 New Relic、Datadog 或 Prometheus 监控应用的性能,找出瓶颈并进行优化。
通过以上方法,你可以显著提升 ThinkPHP 在 Ubuntu 上的响应速度。根据具体情况选择合适的优化策略。