PHP opcache 配置、状态与清除

Posted by Sunday on 2019-03-18

nginx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
server {
listen 80;
server_name 192.168.10.21;
root /data/web/opcache-status;
index index.php index.html;

location / {
try_files $uri $uri/ /index.php?$query_string;
}

location ~ \.php {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}

access_log /data/logs/nginx/opcache-status.log;
error_log /data/logs/nginx/opcache-status.err;
}

opcache 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
zend_extension = opcache.so

;确定是否启用了Zend OPCache
opcache.enable=1

;确定是否启用了Zend OPCache CLI
opcache.enable_cli=1

;OPcache共享内存存储大小。
opcache.memory_consumption=512

;暂存池中字符串的占内存总量
opcache.interned_strings_buffer=64

;OPcache哈希表中的最大键数, 控制内存中最多可以缓存多少个PHP文件
opcache.max_accelerated_files=100000

;配置为1时,会根据revalidate_freq设定的值检查更新代码;设置为0时,永不检查;
设置为0时,需要reload php 或调用 opcache_reset 函数清除才能看到最新代码效果
;对于开发/测试,设置1
;对于生产环境,设置0
opcache.validate_timestamps=0

;设置缓存的过期时间,默认2,检测php代码是否更改间隔(秒),若值为0表示每次请求都会检查你的PHP代码是否更新(增加开销)
opcache.revalidate_freq=2

;是否保存文件/函数的注释,建议保持启用,因为有些库依赖它
opcache.save_comments=1

;打开快速关闭, 打开这个在PHP Request Shutdown的时候回收内存的速度会提高,在7.2.0中被移除,会自动开启
opcache.fast_shutdown=1 ;

计算php文件数

1
find . -type f -print | grep php | wc -l

常用函数

1
2
3
4
5
6
opcache_compile_file($php_file); #预生成opcode缓存
opcache_is_script_cached($php_file) #查看是否生成opcode缓存
opcache_invalidate($php_file, true) #清除单个缓存
opcache_reset(); #清空缓存
opcache_get_status(); #获取缓存的状态信息
opcache_get_configuration(); #获取缓存的配置信息

opcache命中状态

1
2
cd /data/web/opcache-status
wget https://raw.githubusercontent.com/rlerdorf/opcache-status/master/opcache.php

访问 http://192.168.10.21/opcache.php
opcache-status
opcache-status-scripts

opcache清除配置

1
2
3
4
5
cd /data/web/opcache-status
echo "<?php opcache_reset(); ?>" > opcache-reset.php

#清除所有opcache
curl http://192.168.10.21/opcache-reset.php

opcache-clean-after

若是采用软链接发布代码请参考 如何正确发布PHP代码

链接

PHP官网opcache-reset文档
如何正确发布PHP代码
查看opcache状态插件