<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>队列 on 施国鹏 (seth-shi)</title><link>https://sethix.com/zh-cn/tags/%E9%98%9F%E5%88%97/</link><description>Recent content in 队列 on 施国鹏 (seth-shi)</description><generator>Hugo -- gohugo.io</generator><language>zh-cn</language><lastBuildDate>Tue, 06 Jul 2021 12:43:13 +0800</lastBuildDate><atom:link href="https://sethix.com/zh-cn/tags/%E9%98%9F%E5%88%97/index.xml" rel="self" type="application/rss+xml"/><item><title>static 静态变量引起 Laravel 中队列一个 Bug</title><link>https://sethix.com/zh-cn/posts/2021070612/</link><pubDate>Tue, 06 Jul 2021 12:43:13 +0800</pubDate><guid>https://sethix.com/zh-cn/posts/2021070612/</guid><description>环境 PHP_VERSION=7.4 laravel/framework: ^7.0 静态变量 很多编程语言对于静态变量的解释都是: 与程序有着相同生命周期的变量, 只初始化一次 不过由于PHP的常用运行环境是php-fpm模式,每次请求结束进程就会被回收, 静态变量不会常驻内存(只会在此次请求生效) PHP 官网是这么介绍的 变量范围的另一个重要特性是静态变量（static variable）。静态变量仅在局部函数域中存在，但当程序执行离开此作用域时，其值并不丢失。看看下面的例子：https://www.php.net/manual/zh/language.variables.scope.php
前言 项目中有以下伪代码逻辑: 因为数据库中的json_data是一个json字符串,所以不必每次获取都解析, 使用static变量修饰符使得下一次访问不需要再次解析 &amp;lt;?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class AttributeRequestLog extends Model { public function getJsonData($key) { static $jsonData; if (is_null($jsonData)) { $jsonData = json_decode($this-&amp;gt;attributes[&amp;#39;json_data&amp;#39;], true); } return $jsonData[$key] ?? null; } } 因为之前没上队列处理异步任务, 程序一直没问题. 直到某一天上了队列之后, 有同事反馈, 有异常数据上报. 赶紧排查了一下日志, 发现队列中的日志打点数据有问题,随后增加更多打点, 最后定位到了这个地方.
由于Laravel的队列采用CLI运行模式, 这时候处理的任务都是后台运行 队列启动时载入代码, 直到队列进程被杀死, 否则代码也不会更新, 分析源码 队列的启动命令: php artisan queue:work 找到启动文件src\Illuminate\Queue\Console\WorkCommand.php是一个继承于Illuminate\Console\Command的类,运行artisan的时候, 会运行其的handle方法 Laravel Laravel 实际上是拿到队列的驱动,然后转到worker去运行任务, 传递了一个参数once是否只运行一个任务,这里我们直接查看daemon方法 转到src\Illuminate\Queue\Worker.</description></item></channel></rss>