laravel 用数据库实现消息队列

.env修改配置

QUEUE_DRIVER=database

执行命令行:

php artisan queue:table
php artisan migrate

创建jobs表
然后创建一个任务:

php artisan make:job SendMessage

SendMessage.php代码如下:



namespace App\Jobs;

use App\Notice;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class SendMessage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $_notice;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Notice $notice)
    {
        //
        $this->_notice = $notice;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //通知每个用户
        $users = User::all();
        foreach ($users as $user) {
            $user->addNotice($this->_notice);
        }
    }
}

User模型:

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    //收到通知
    public function notices()
    {
        return $this->belongsToMany(\App\Notice::class, 'user_notice', 'user_id', 'notice_id')
            ->withPivot(['user_id', 'notice_id']);
    }
    //添加通知
    public function addNotice( $notice )
    {
        return $this->notices()->save($notice);
    }
}

执行队列代码需要在控制器执行以下代码:

$notice = Notice::create(request(['title', 'content']));
//消息队列
dispatch(new \App\jobs\SendMessage($notice));

注意:需要启动队列

php artisan queue:work
//或者使用常驻(linux)
nohup php artisan queue:work >> /dev/queue.log &

你可能感兴趣的:(php,php学习)