Last active
December 27, 2020 13:01
-
-
Save rpkamp/f9c21110e441fb35c15c3a8d3d0361e1 to your computer and use it in GitHub Desktop.
Google Cloud Platform pub/sub PHP example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"require": { | |
"google/cloud-pubsub": "^0.12.0" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require 'vendor/autoload.php'; | |
use Google\Cloud\PubSub\PubSubClient; | |
$pubSub = new PubSubClient([ | |
'projectId' => 'my_project' | |
]); | |
$topic = $pubSub->topic('my_topic'); | |
if (!$topic->exists()) { | |
$pubSub->createTopic('my_topic'); | |
} | |
// Publish a message to the topic. | |
$topic->publish([ | |
'data' => 'My new message.', | |
'attributes' => [ | |
'location' => 'Detroit' | |
] | |
]); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require 'vendor/autoload.php'; | |
use Google\Cloud\PubSub\PubSubClient; | |
$pubSub = new PubSubClient([ | |
'projectId' => 'my_project' | |
]); | |
$subscription = $pubSub->subscription('my_subscription'); | |
if (!$subscription->exists()) { | |
$pubSub->subscribe('my_subscription', 'my_topic'); | |
} | |
// TODO: listen for SIGTERM and SIGKILL and stop the loop | |
while (true) { | |
$messages = $subscription->pull(); | |
foreach ($messages as $message) { | |
echo '>> New message, received at ', date('Y-m-d H:i:s'), "\n"; | |
echo 'Data: ', $message->data() , "\n"; | |
echo 'Location: ', $message->attribute('location'), "\n\n"; | |
$subscription->acknowledge($message); | |
} | |
} |
This setup is only meant for pull. For push, please follow the examples provided by google itself.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks for this. I'm stuck though, I can't get the notifications in the server. I'm simply logging it and responding with 200 status code. But I Don't think google is sending anything to the server when I send a test notification. I'm using push.