举例说明如何在存储分区上设置保留政策。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
C#
如需了解详情,请参阅 Cloud Storage C# API 参考文档。
using Google.Cloud.Storage.V1;
using System;
using static Google.Apis.Storage.v1.Data.Bucket;
public class SetRetentionPolicySample
{
/// <summary>
/// Sets the bucket's retention policy.
/// </summary>
/// <param name="bucketName">The name of the bucket.</param>
/// <param name="retentionPeriod">The duration in seconds that objects need to be retained. The retention policy enforces a minimum retention
/// time for all objects contained in the bucket, based on their creation time. Any
/// attempt to overwrite or delete objects younger than the retention period will
/// result in a PERMISSION_DENIED error. An unlocked retention policy can be modified
/// or removed from the bucket via a storage.buckets.update operation. A locked retention
/// policy cannot be removed or shortened in duration for the lifetime of the bucket.
/// Attempting to remove or decrease the period of a locked retention policy will result
/// in a PERMISSION_DENIED error.</param>
public RetentionPolicyData SetRetentionPolicy(
string bucketName = "your-unique-bucket-name",
long retentionPeriod = 10)
{
var storage = StorageClient.Create();
var bucket = storage.GetBucket(bucketName);
bucket.RetentionPolicy = new RetentionPolicyData { RetentionPeriod = retentionPeriod };
bucket = storage.UpdateBucket(bucket);
Console.WriteLine($"Retention policy for {bucketName} was set to {retentionPeriod}");
return bucket.RetentionPolicy;
}
}
C++
如需了解详情,请参阅 Cloud Storage C++ API 参考文档。
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::chrono::seconds period) {
StatusOr<gcs::BucketMetadata> original =
client.GetBucketMetadata(bucket_name);
if (!original) throw std::runtime_error(original.status().message());
StatusOr<gcs::BucketMetadata> patched_metadata = client.PatchBucket(
bucket_name,
gcs::BucketMetadataPatchBuilder().SetRetentionPolicy(period),
gcs::IfMetagenerationMatch(original->metageneration()));
if (!patched_metadata) {
throw std::runtime_error(patched_metadata.status().message());
}
if (!patched_metadata->has_retention_policy()) {
std::cout << "The bucket " << patched_metadata->name()
<< " does not have a retention policy set.\n";
return;
}
std::cout << "The bucket " << patched_metadata->name()
<< " retention policy is set to "
<< patched_metadata->retention_policy() << "\n";
}
Go
如需了解详情,请参阅 Cloud Storage Go API 参考文档。
ctx := context.Background()
bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
RetentionPolicy: &storage.RetentionPolicy{
RetentionPeriod: retentionPeriod,
},
}
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
return err
}
Java
如需了解详情,请参阅 Cloud Storage Java API 参考文档。
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
public class SetRetentionPolicy {
public static void setRetentionPolicy(
String projectId, String bucketName, Long retentionPeriodSeconds) throws StorageException {
// The ID of your GCP project
// String projectId = "your-project-id";
// The ID of your GCS bucket
// String bucketName = "your-unique-bucket-name";
// The retention period for objects in bucket
// Long retentionPeriodSeconds = 3600L; // 1 hour in seconds
Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
Bucket bucketWithRetentionPolicy =
storage.update(
BucketInfo.newBuilder(bucketName).setRetentionPeriod(retentionPeriodSeconds).build());
System.out.println(
"Retention period for "
+ bucketName
+ " is now "
+ bucketWithRetentionPolicy.getRetentionPeriod());
}
}
Node.js
如需了解详情,请参阅 Cloud Storage Node.js API 参考文档。
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';
// The retention period for objects in bucket
// const retentionPeriod = 3600; // 1 hour in seconds
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');
// Creates a client
const storage = new Storage();
async function setRetentionPolicy() {
const [metadata] = await storage
.bucket(bucketName)
.setRetentionPeriod(retentionPeriod);
console.log(
`Bucket ${bucketName} retention period set for ${metadata.retentionPolicy.retentionPeriod} seconds.`
);
}
setRetentionPolicy().catch(console.error);
PHP
如需了解详情,请参阅 Cloud Storage PHP API 参考文档。
use Google\Cloud\Storage\StorageClient;
/**
* Sets a bucket's retention policy.
*
* @param string $bucketName The name of your Cloud Storage bucket.
* @param int $retentionPeriod The retention period for objects in bucket, in seconds.
*/
function set_retention_policy($bucketName, $retentionPeriod)
{
// $bucketName = 'my-bucket';
// $retentionPeriod = 3600;
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$bucket->update([
'retentionPolicy' => [
'retentionPeriod' => $retentionPeriod
]]);
printf('Bucket %s retention period set to %s seconds' . PHP_EOL, $bucketName,
$retentionPeriod);
}
Python
如需了解详情,请参阅 Cloud Storage Python API 参考文档。
from google.cloud import storage
def set_retention_policy(bucket_name, retention_period):
"""Defines a retention policy on a given bucket"""
# bucket_name = "my-bucket"
# retention_period = 10
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
bucket.retention_period = retention_period
bucket.patch()
print(
"Bucket {} retention period set for {} seconds".format(
bucket.name, bucket.retention_period
)
)
Ruby
如需了解详情,请参阅 Cloud Storage Ruby API 参考文档。
def set_retention_policy bucket_name:, retention_period:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# The retention period for objects in bucket
# retention_period = 3600 # 1 hour in seconds
require "google/cloud/storage"
storage = Google::Cloud::Storage.new
bucket = storage.bucket bucket_name
bucket.retention_period = retention_period
puts "Retention period for #{bucket_name} is now #{bucket.retention_period} seconds."
end
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。