Laravel框架 之 队列

本文的示例代码参考queue

开始

  • 开始

  • 路由

  • 通知

  • 队列

    • 同步

    • 异步

开始

composer create-project laravel/laravel queue --prefer-dist "5.5.*"
# cd queue
vim composer.json
# add dingo/api to require
"dingo/api": "2.0.0-alpha1"
composer update

php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"
vim .env
# add api config to .env
API_STANDARDS_TREE=prs
API_SUBTYPE=queue
API_PREFIX=api
API_VERSION=v1
API_DEBUG=true

路由

php artisan make:controller Api/NotificationsController

vim app/Http/Controllers/Api/NotificationsController.php
response->array(['msg'=>'notification']);
    }
}
vim routes/api.php
version('v1', [
    'namespace' => 'App\Http\Controllers\Api'
],function($api) {
    $api->post('notifications', 'NotificationsController@create')
        ->name('api.NotificationsController.create');
});
  • 测试
php artisan serve
curl -X POST localhost:8000/api/notifications | json
{
  "msg": "notification"
}

通知

php artisan make:notification MailNotification

vim app/Notifications/MailNotification.php
msg = $msg;
    }

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('你有一条新的消息 ' . $this->msg);
    }
}
vim app/Http/Controllers/Api/NotificationsController.php
notify(new MailNotification('hello laravel queue'));
        return $this->response->array(['msg'=>'notification']);
    }
}
vim .env
# mod mail config in .env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.qq.com
MAIL_PORT=25
[email protected]
MAIL_PASSWORD=***
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME=queue
  • 测试
php artisan serve
curl -X POST localhost:8000/api/notifications | json
{
  "msg": "notification"
}

登录[email protected]查收邮件

队列

同步

vim app/Notifications/MailNotification.php
msg = $msg;
    }

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('你有一条新的消息 ' . $this->msg);
    }
}
  • 测试
php artisan serve
curl -X POST localhost:8000/api/notifications | json
{
  "msg": "notification"
}

异步

sed -i 's/QUEUE_DRIVER=sync/QUEUE_DRIVER=redis/g' .env

MacOS下sed修改文件明了和Ubuntu不同: sed -i "" 's/QUEUE_DRIVER=sync/QUEUE_DRIVER=redis/g' .env

composer require predis/predis
docker run --name laravel-redis -p 6379:6379 -d redis
  • 测试
php artisan serve
curl -X POST localhost:8000/api/notifications | json
{
  "msg": "notification"
}

你可能感兴趣的:(Laravel框架 之 队列)