hyperf/zh/async-queue.md

100 lines
1.9 KiB
Markdown
Raw Normal View History

2019-03-30 15:00:10 +08:00
# 异步队列
异步队列区别于 `RabbitMQ` `Kafka` 等消息队列,它只提供一种异步处理和异步延时处理的能力。
2019-03-30 22:53:32 +08:00
## 安装
```bash
2019-04-10 14:28:15 +08:00
composer require hyperf/async-queue
2019-03-30 22:53:32 +08:00
```
2019-03-30 15:00:10 +08:00
## 配置
暂时只支持 `Redis Driver`
2019-04-10 14:28:15 +08:00
| 配置 | 类型 | 默认值 | 备注 |
|:-------------:|:------:|:-------------------------------------------:|:------------------:|
| driver | string | Hyperf\AsyncQueue\Driver\RedisDriver::class | 无 |
| channel | string | queue | 队列前缀 |
| retry_seconds | int | 5 | 失败后重新尝试间隔 |
| processes | int | 1 | 消费进程数 |
2019-03-30 15:00:10 +08:00
```php
<?php
return [
'default' => [
2019-04-10 14:28:15 +08:00
'driver' => Hyperf\AsyncQueue\Driver\RedisDriver::class,
2019-03-30 15:00:10 +08:00
'channel' => 'queue',
'retry_seconds' => 5,
'processes' => 1,
],
];
```
## 使用
### 消费消息
组件已经提供了默认子进程,只需要将子进程配置到 `processes.php` 中即可。
```php
<?php
return [
2019-04-10 14:28:15 +08:00
Hyperf\AsyncQueue\Process\ConsumerProcess::class,
2019-03-30 15:00:10 +08:00
];
```
### 发布消息
首先我们定义一个消息,如下
```php
<?php
declare(strict_types=1);
namespace App\Jobs;
2019-04-10 14:28:15 +08:00
use Hyperf\AsyncQueue\Job;
2019-03-30 15:00:10 +08:00
class ExampleJob extends Job
{
public function handle()
{
var_dump('hello world');
}
}
```
发布消息
```php
<?php
declare(strict_types=1);
use Psr\Container\ContainerInterface;
2019-04-10 14:28:15 +08:00
use Hyperf\AsyncQueue\Driver\DriverFactory;
2019-03-30 15:00:10 +08:00
class DemoService
{
protected $driver;
2019-05-13 02:25:03 +08:00
public function __construct(DriverFactory $driverFactory)
2019-03-30 15:00:10 +08:00
{
2019-05-13 02:25:03 +08:00
$this->driver = $driverFactory->get('default');
2019-03-30 15:00:10 +08:00
}
public function publish()
{
return $this->driver->push(new ExampleJon());
}
}
```