Google Cloud Pub/Sub

From XennisWiki
Jump to: navigation, search

Service of the Google Cloud Platform to queue messages.


Enable the API

gcloud services enable

Go libraray

Create topic if it not exists

func createTopicIfNotExists(ctx context.Context, c *pubsub.Client, name string) (*pubsub.Topic, error) {
	t := c.Topic(name)
	if ok, err := t.Exists(ctx); err != nil || ok {
		return t, err
	return c.CreateTopic(ctx, name)

Create subscription of not exists

func createSubIfNotExists(ctx context.Context, c *pubsub.Client, t *pubsub.Topic, name string) (*pubsub.Subscription, error) {
	s := c.Subscription(name)
	if ok, err := s.Exists(ctx); err != nil || ok {
		config, err := s.Config(ctx) // panics, if the topic name is bad (happens when the topic was deleted, but not the subscription)
		if err != nil {
			return nil, err
		if config.Topic == nil || config.Topic.ID() != t.ID() {
			return nil, fmt.Errorf("pub/sub sub %s exists, but has not %s as topic", s.ID(), t.ID())
		return s, err
	return c.CreateSubscription(ctx, name, pubsub.SubscriptionConfig{
		Topic:       t,
		AckDeadline: 20 * time.Second,

PHP library


Use Composer to install google/cloud-pubsub.

Publish a message

Set the service account key as a constant

        "type": "service_account",

Publish a message

$message = 'Hello World'
$attributes = ['id' => 101];

$pubsub = new PubSubClient([
	'keyFile' => json_decode(GCP_APPLICATION_KEY, true)
$topic = $pubsub->topic('some-topic');
	'data' => $message,
	'attributes' => $attributes


Seek in subscription

gcloud beta pubsub subscriptions seek <sub-name> --time yyyy-mm-ddTHH:MM:SS

See also

External links