Google Cloud Pub/Sub

From XennisWiki
Jump to: navigation, search

Service of the Google Cloud Platform to queue messages.

Setup

Enable the API

gcloud services enable pubsub.googleapis.com

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

Installation

Use Composer to install google/cloud-pubsub.

Publish a message

Set the service account key as a constant

define('GCP_APPLICATION_KEY', '{
        "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');
$topic->publish([
	'data' => $message,
	'attributes' => $attributes
]);

Commands

Seek in subscription

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

See also

External links