Laravel大量数据库查询导致php进程内存耗尽 |
您所在的位置:网站首页 › flutter20更新 › Laravel大量数据库查询导致php进程内存耗尽 |
最近做了一个Laravel命令行工具来处理大量用户数据。奇怪的是,每次处理到十多万条数据的时候就报如下内存耗尽错误: PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in [....] 出现该错误的原因是php.ini中默认设置php进程最大可以使用128M内存,一旦超过就会导致新分配内存失败。 可以使用以下语句将限制临时提高到1G内存: ini_set('memory_limit', '1024M'); 但这种方法毕竟是权宜之计,如果未来数据量指数级增加还是会出问题,所以必须找到内存暴涨的根源。 经过百般查找,把问题定位到了一个不起眼的DB查找语句: ... $item = DB::table('表名')->where('user_id', $user_id)->where...... ... 在Laravel官方文档找到以下说明: Query LoggingBy default, Laravel keeps a log in memory of all queries that have been run for the current request. However, in some cases, such as when inserting a large number of rows, this can cause the application to use excess memory. To disable the log, you may use the disableQueryLog method: DB::connection()->disableQueryLog();To get an array of the executed queries, you may use the getQueryLog method: $queries = DB::getQueryLog(); 意思是Laravel框架默认存储每次请求(每次命令行执行也相当于一次请求)的所有数据库查询语句!!!在普通的http中数据库请求语句并不多,所有不会导致问题,但是需要大量数据库查询的命令行工具就显然不能这么干,解决方法是禁用query日志: DB::connection()->disableQueryLog(); //禁用query log 禁用query日志之后php进程的内存消耗一直维持在二十几兆,问题解决! |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |