# 5.11 杂项

## 消息队列

当前消息队列支持Redis、RabbitMQ、Kafka，使用方法也很简单，一般只需要关心set和get方法即可。

### Redis作为消息队列
```php
//准备一个队列
$redisQueue = $this->getObject(\PG\MSF\Queue\Redis::class, ['p1']);
// Enqueue入队，默认队列为default
$res = yield $redisQueue->set(string $data, string $queue = 'default');
// Dequeue出队
$res = yield $redisQueue->get(string $queue = 'default');
```

### RabbitMQ消息队列
```php
//首先需要配置自己的队列
$config['amqp'] = [
    'rabbit' => [
        'host' => '127.0.0.1',
        'port' => '5672'
    ]
];

//准备一个队列，并配置路由key，默认为default
$rabbit = $this->getObject(PG\MSF\Queue\RabbitMQ::class, 
 ['rabbit', $routing_key = 'default']);
// Enqueue入队，默认队列为default
$res = yield $rabbit->set(string $data, string $queue = 'default');
// Dequeue出队，默认直接Ack，也可以手工Ack
$res = yield $rabbit->get(string $queue = 'default', $isAck = true);
```
### Kafka作为消息队列
```php
//首先需要配置自己的队列
$config['kafka'] = [
    'local' => [
        'socket.keepalive.enable' => true,
        'bootstrap.servers' => '127.0.0.1:9092',
        'group.id' => 'default'
    ]
];
//准备一个队列
$kafka = $this->getObject(PG\MSF\Queue\Kafka::class, ['local']);
// Enqueue入队，默认队列为default
$res = yield $kafka->set(string $data, string $queue = 'default');
// Dequeue
$res = yield $kafka->get(string $queue = 'default');
```

## Shell Exec

在写定时任务的时候，难免会使用到`shell_exec`这个php函数，但是这个函数是阻塞的，
所以我们提供了异步协程执行shell脚本的特性,使用方式也很简单。

```php
//result为shell执行后屏幕的输出，如果执行失败，会返回false
$result = yield $this->getObject(\PG\MSF\Coroutine\Shell::class)->goExec('ps aux | grep msf');
```

# links
  * [目录](../README.md)
  * 上一节: [多语言](5.10-多语言.md)
  * 下一节: [小结](5.12-小结.md)