|
| 1 | +# Google Pub Sub transport |
| 2 | + |
| 3 | +A transport for [Google Pub Sub](https://cloud.google.com/pubsub/docs/) cloud MQ. |
| 4 | +It uses internally official google sdk library [google/cloud-pubsub](https://packagist.org/packages/google/cloud-pubsub) |
| 5 | + |
| 6 | +* [Installation](#installation) |
| 7 | +* [Create context](#create-context) |
| 8 | +* [Send message to topic](#send-message-to-topic) |
| 9 | +* [Consume message](#consume-message) |
| 10 | + |
| 11 | +## Installation |
| 12 | + |
| 13 | +```bash |
| 14 | +$ composer require enqueue/gps |
| 15 | +``` |
| 16 | + |
| 17 | +## Create context |
| 18 | + |
| 19 | +To enable the Google Cloud Pub/Sub Emulator, set the `PUBSUB_EMULATOR_HOST` environment variable. |
| 20 | +There is a handy docker container [google/cloud-sdk](https://hub.docker.com/r/google/cloud-sdk/). |
| 21 | + |
| 22 | +```php |
| 23 | +<?php |
| 24 | +use Enqueue\Gps\GpsConnectionFactory; |
| 25 | + |
| 26 | +putenv('PUBSUB_EMULATOR_HOST=http://localhost:8900'); |
| 27 | + |
| 28 | +$connectionFactory = new GpsConnectionFactory(); |
| 29 | + |
| 30 | +$psrContext = $connectionFactory->createContext(); |
| 31 | +``` |
| 32 | + |
| 33 | +## Send message to topic |
| 34 | + |
| 35 | +Before you can send message you have to declare a topic. |
| 36 | +The operation creates a topic on a broker side. |
| 37 | +Google allows messages to be sent only to topic. |
| 38 | + |
| 39 | +```php |
| 40 | +<?php |
| 41 | +/** @var \Enqueue\Gps\GpsContext $psrContext */ |
| 42 | + |
| 43 | +$fooTopic = $psrContext->createTopic('foo'); |
| 44 | +$message = $psrContext->createMessage('Hello world!'); |
| 45 | + |
| 46 | +$psrContext->declareTopic($fooTopic); |
| 47 | + |
| 48 | +$psrContext->createProducer()->send($fooTopic, $message); |
| 49 | +``` |
| 50 | + |
| 51 | +## Consume message: |
| 52 | + |
| 53 | +Before you can consume message you have to subscribe a queue to the topic. |
| 54 | +Google does not allow consuming message from the topic directly. |
| 55 | + |
| 56 | +```php |
| 57 | +<?php |
| 58 | +/** @var \Enqueue\Gps\GpsContext $psrContext */ |
| 59 | + |
| 60 | +$fooTopic = $psrContext->createTopic('foo'); |
| 61 | +$fooQueue = $psrContext->createQueue('foo'); |
| 62 | + |
| 63 | +$psrContext->subscribe($fooTopic, $fooQueue); |
| 64 | + |
| 65 | +$consumer = $psrContext->createConsumer($fooQueue); |
| 66 | +$message = $consumer->receive(); |
| 67 | + |
| 68 | +// process a message |
| 69 | + |
| 70 | +$consumer->acknowledge($message); |
| 71 | +// $consumer->reject($message); |
| 72 | +``` |
| 73 | + |
| 74 | +[back to index](../index.md) |
0 commit comments