AMQP组件

    1. return [
    2. 'default' => [
    3. 'host' => 'localhost',
    4. 'port' => 5672,
    5. 'user' => 'guest',
    6. 'password' => 'guest',
    7. 'vhost' => '/',
    8. 'pool' => [
    9. 'min_connections' => 1,
    10. 'max_connections' => 10,
    11. 'connect_timeout' => 10.0,
    12. 'wait_timeout' => 3.0,
    13. 'heartbeat' => -1,
    14. 'params' => [
    15. 'insist' => false,
    16. 'login_method' => 'AMQPLAIN',
    17. 'login_response' => null,
    18. 'locale' => 'en_US',
    19. 'connection_timeout' => 3.0,
    20. 'context' => null,
    21. 'keepalive' => false,
    22. 'heartbeat' => 0,
    23. ],
    24. ],
    25. ];

    使用 generator 工具新建一个 producer

    1. <?php
    2. declare(strict_types=1);
    3. namespace App\Amqp\Producers;
    4. use Hyperf\Amqp\Message\ProducerMessage;
    5. /**
    6. * DemoProducer
    7. * @Producer(exchange="hyperf", routingKey="hyperf")
    8. */
    9. class DemoProducer extends ProducerMessage
    10. {
    11. public function __construct($id)
    12. {
    13. $user = User::where('id', $id)->first();
    14. $this->payload = [
    15. 'id' => $id,
    16. 'data' => $user->toArray()
    17. ];
    18. }
    19. }

    通过container获取Producer实例,即可投递消息。以下实例直接使用ApplicationContext获取Producer其实并不合理,container具体使用请到di模块中查看。

    1. php bin/hyperf.php gen:amqp-consumer DemoConsumer

    在DemoConsumer文件中,我们可以修改Consumer注解对应的字段来替换对应的 exchangeroutingKey 和 。其中 $data 就是解析后的元数据。示例如下。