Google Cloud Functions integration with PubSub

1. Create a test topic

gcloud pubsub topics create bartek-test-topic

Created topic [projects/xyz-123/topics/bartek-test-topic].
2. Create a Google Cloud Function called bartek-test-function using UI and configure it to read from PubSub bartek-test-topic with code:

package com.example;

import com.example.Example.PubSubMessage;
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import java.util.Base64;
import java.util.Map;
import java.util.logging.Logger;

public class Example implements BackgroundFunction<PubSubMessage> {
  private static final Logger logger = Logger.getLogger(Example.class.getName());

  @Override
  public void accept(PubSubMessage message, Context context) {
    String data = message.data != null
      ? "received " + new String(Base64.getDecoder().decode(message.data)) 
      : "Hello, World";
    logger.info(data + ", attributes=" + message.attributes + ", messageId=" + message.messageId + ", publishTime=" + message.publishTime);
  }

  public static class PubSubMessage {
    String data;
    Map<String, String> attributes;
    String messageId;
    String publishTime;
  }
}

3. Send message to PubSub topic:

 gcloud pubsub topics publish bartek-test-topic --message="hello from gcloud" --attribute="origin=gcloud-sample,username=bartek"
messageIds:
- '1740371803360178'

Output in GCP logs:

View logs of executed google cloud function

Leave a comment