删除架构

删除架构资源。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C++

试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C++ 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub C++ API 参考文档。

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

namespace pubsub = ::google::cloud::pubsub;
[](pubsub::SchemaServiceClient client, std::string const& project_id,
   std::string const& schema_id) {
  google::pubsub::v1::DeleteSchemaRequest request;
  request.set_name(pubsub::Schema(project_id, schema_id).FullName());
  auto status = client.DeleteSchema(request);
  // Note that kNotFound is a possible result when the library retries.
  if (status.code() == google::cloud::StatusCode::kNotFound) {
    std::cout << "The schema was not found\n";
    return;
  }
  if (!status.ok()) throw std::runtime_error(status.message());

  std::cout << "Schema successfully deleted\n";
}

C#

试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C# 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub C# API 参考文档。

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。


using Google.Cloud.PubSub.V1;

public class DeleteSchemaSample
{
    public void DeleteSchema(string projectId, string schemaId)
    {
        SchemaServiceClient schemaService = SchemaServiceClient.Create();
        SchemaName schemaName = SchemaName.FromProjectSchema(projectId, schemaId);
        schemaService.DeleteSchema(schemaName);
    }
}

Go

试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Go 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Go API 参考文档。

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

import (
	"context"
	"fmt"
	"io"

	pubsub "cloud.google.com/go/pubsub/v2/apiv1"
	"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb"
)

func deleteSchema(w io.Writer, projectID, schemaID string) error {
	// projectID := "my-project-id"
	// schemaID := "my-schema"
	ctx := context.Background()
	client, err := pubsub.NewSchemaClient(ctx)
	if err != nil {
		return fmt.Errorf("pubsub.NewSchemaClient: %w", err)
	}
	defer client.Close()

	req := &pubsubpb.DeleteSchemaRequest{
		Name: fmt.Sprintf("projects/%s/schemas/%s", projectID, schemaID),
	}
	if err := client.DeleteSchema(ctx, req); err != nil {
		return fmt.Errorf("client.DeleteSchema: %w", err)
	}
	fmt.Fprintf(w, "Deleted schema: %s", schemaID)
	return nil
}

Java

试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Java 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Java API 参考文档。

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

import com.google.cloud.pubsub.v1.SchemaServiceClient;
import com.google.pubsub.v1.SchemaName;

public class DeleteSchema {

  public static void main(String[] args) throws Exception {
    String projectId = "example-project-id";
    String schemaId = "example-schema-id";
    deleteSchema(projectId, schemaId);
  }

  public static void deleteSchema(String projectId, String schemaId) throws Exception {
    try (SchemaServiceClient client = SchemaServiceClient.create()) {
      String name = SchemaName.of(projectId, schemaId).toString();
      client.deleteSchema(name);
      System.out.println("Deleted schema: " + name);
    }
  }
}

Node.js

试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Node.js 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Node.js API 参考文档。

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

'use strict';

const {SchemaServiceClient} = require('@google-cloud/pubsub-api');
const {status} = require('@grpc/grpc-js');

const client = new SchemaServiceClient();

/**
 * Use the deleteSchema method
 *
 * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id')
 * @param {string} schemaId - ID of the Schema (for example, 'example-schema-id')
 */
async function deleteSchema(projectId, schemaId) {
  try {
    // Format the resource name from project and schema identifiers
    const name = client.schemaPath(projectId, schemaId);

    const request = {
      name,
    };

    await client.deleteSchema(request);
    console.log(`Deleted schema: ${name}`);
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Schema not found: ${projectId}/${schemaId}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied for schema: ${projectId}/${schemaId}`);
    } else {
      console.error(`Failed to delete schema: ${err.message}`);
    }
  }
}

module.exports = { deleteSchema };

Node.js

在尝试此示例之前,请按照《Pub/Sub 快速入门:使用客户端库》中的 Node.js 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Node.js API 参考文档。

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID';

// Imports the Google Cloud client library
import {PubSub} from '@google-cloud/pubsub';

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function deleteSchema(schemaNameOrId: string) {
  const schema = pubSubClient.schema(schemaNameOrId);
  const name = await schema.getName();
  await schema.delete();
  console.log(`Schema ${name} deleted.`);
}

PHP

试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 PHP 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub PHP API 参考文档。

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

use Google\Cloud\PubSub\PubSubClient;

/**
 * Delete a schema.
 *
 * @param string $projectId
 * @param string $schemaId
 */
function delete_schema($projectId, $schemaId)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);

    $schema = $pubsub->schema($schemaId);

    if ($schema->exists()) {
        $schema->delete();

        printf('Schema %s deleted.', $schema->name());
    } else {
        printf('Schema %s does not exist.', $schema->name());
    }
}

Python

试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Python 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Python API 参考文档。

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

import google.api_core.exceptions
from google.cloud import pubsub_v1

client = pubsub_v1.SchemaServiceClient()


def delete_schema(project_id: str, schema_id: str) -> None:
    """Deletes a Pub/Sub schema.

    Args:
        project_id: The Google Cloud project ID (for example, 'example-project-id')
        schema_id: ID of the Schema (for example, 'example-schema-id')
    """
    name = client.schema_path(project_id, schema_id)

    try:
        client.delete_schema(name=name)
        print(f"Deleted schema: {name}")
    except google.api_core.exceptions.NotFound:
        print(f"Schema does not exist: {name}")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"Failed to delete schema due to an API error: {e}")

Ruby

试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Ruby 设置说明进行操作。 如需了解详情,请参阅 Pub/Sub Ruby API 参考文档。

如需向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

# schema_id = "your-schema-id"

pubsub = Google::Cloud::PubSub.new
schemas = pubsub.schemas

result = schemas.delete_schema name: pubsub.schema_path(schema_id)

puts "Schema #{schema_id} deleted."

Rust

use google_cloud_pubsub::client::SchemaService;

pub async fn sample(
    client: &SchemaService,
    project_id: &str,
    schema_id: &str,
) -> anyhow::Result<()> {
    client
        .delete_schema()
        .set_name(format!("projects/{project_id}/schemas/{schema_id}"))
        .send()
        .await?;

    println!("successfully deleted schema");
    Ok(())
}

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅Google Cloud 示例浏览器。