跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

GoogleCloudPubSub

GoogleCloudPubSub is a PubSub implementation backed by Google Cloud Pub/Sub. It delivers events across processes and hosts using Google Cloud topics and subscriptions, with ordered delivery and message acknowledgment.

Use it for distributed deployments on Google Cloud. For single-process delivery, use EventEmitterPubSub. For Redis, use RedisStreamsPubSub.

Each topic maps to a Google Cloud topic. Subscriptions with a group share a subscription. Members compete for events. Subscriptions without a group create a per-instance subscription. Every instance receives every event.

Installation
Installation的直接链接

npm install @mastra/google-cloud-pubsub

Usage example
Usage example的直接链接

Pass a Google Cloud client configuration, such as a project ID.

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { GoogleCloudPubSub } from '@mastra/google-cloud-pubsub'

export const mastra = new Mastra({
pubsub: new GoogleCloudPubSub({
projectId: 'my-project',
}),
})

Constructor parameters
Constructor parameters的直接链接

config:

ClientConfig
Configuration for the Google Cloud Pub/Sub client, including credentials and project ID. See the @google-cloud/pubsub client documentation for all fields.

Methods
Methods的直接链接

GoogleCloudPubSub implements the PubSub contract. The methods below are specific to this implementation.

init(topicName, group?)
inittopicname-group的直接链接

Creates the topic and a subscription if they don't already exist, and returns the subscription. subscribe calls this internally, so you rarely call it directly.

await pubsub.init('workflow.events')

subscribe(topic, cb, options?)
subscribetopic-cb-options的直接链接

Subscribes to a topic. With options.group, members of the group share a subscription and compete for events. Without a group, the instance receives every event through its own subscription.

await pubsub.subscribe('workflow.events', (event, ack, nack) => {
console.log(event)
})

flush()
flush的直接链接

Waits for pending acknowledgments to complete.

await pubsub.flush()

destroy(topicName)
destroytopicname的直接链接

Removes the subscription and topic for a topic name. Use this to clean up Google Cloud resources.

await pubsub.destroy('workflow.events')

Acknowledgment
Acknowledgment的直接链接

Each delivered event includes ack and nack functions. Call ack after successful processing to remove the event from the subscription. When neither is called, Google Cloud redelivers the event after its acknowledgment deadline expires.