Todos os produtos
Search
Central de documentação

Object Storage Service:Restore objects

Última atualização: Sep 23, 2026

Objetos Archive, Cold Archive e Deep Cold Archive no OSS são congelados para reduzir os custos de armazenamento. Restaure-os para um estado legível antes de baixá-los, processá-los ou analisá-los.

Como funciona

Uma operação de restauração cria uma réplica temporária e legível de um objeto congelado sem alterar sua classe de armazenamento. O objeto passa pelos seguintes estados:

  1. Estado congelado: estado padrão. O objeto não é legível. Você pode apenas consultar metadados ou excluir o objeto.

  2. Restaurando: após enviar uma solicitação RestoreObject pela primeira vez, o objeto entra neste estado. O servidor processa a solicitação de forma assíncrona.

    • A API retorna 202 Accepted para a primeira solicitação.

    • Uma solicitação duplicada com a mesma prioridade retorna 409 Conflict. Envie uma solicitação com prioridade mais alta para acelerar a restauração.

  3. Restaurado: a réplica temporária é criada e o objeto está legível. Uma solicitação de restauração subsequente retorna 200 OK e estende o período de validade da réplica.

  4. Réplica expirada: a réplica temporária é excluída. Para ler o objeto novamente, envie outra solicitação de restauração.

Escolher uma prioridade de restauração

O tempo de restauração varia conforme a classe de armazenamento e a prioridade. O tempo real de restauração pode variar.

Classe de armazenamento do objeto

Descrição

Archive

Normalmente 1 minuto.

Cold Archive

  • Expedited: a restauração normalmente é concluída em até 1 hora.

  • Standard: a restauração normalmente é concluída entre 2 e 5 horas.

  • Bulk: a restauração normalmente é concluída entre 5 e 12 horas.

Deep Cold Archive

  • Expedited: a restauração normalmente é concluída em até 12 horas.

  • Standard: a restauração normalmente é concluída em até 48 horas.

Escolher um período de validade da réplica

O período de validade da réplica define por quantos dias um objeto restaurado permanece legível sem cobranças adicionais de recuperação de dados. Defina como 1 dia para acesso único, ou um período maior para acessos repetidos, evitando assim custos recorrentes de restauração.

Classe de armazenamento do objeto

Descrição

Archive

Um número inteiro de 1 a 7. A unidade é dia.

Cold Archive

Um número inteiro de 1 a 365. A unidade é dia.

Deep Cold Archive

Um número inteiro de 1 a 365. A unidade é dia.

Executar a restauração

Use um dos métodos a seguir para restaurar um objeto.

Console

O console não oferece suporte à restauração em lote de objetos em uma mesma pasta. Use ossutil, SDKs ou a API para operações em lote.

  1. Faça login no OSS console.

  2. Clique em Buckets, depois clique no nome do bucket de destino.

  3. No painel de navegação à esquerda, escolha Object Management > Objects.

  4. Na coluna Actions do objeto de destino, escolha more > Restore. Na caixa de diálogo, configure Replica Validity Period e Restore Priority.

SDK

Use um SDK para restaurar objetos de forma programática, com automação flexível e tratamento de erros.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the Archive object. Do not include the bucket name in the full path. 
        String objectName = "exampledir/object";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        // Call the shutdown method to release resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            ObjectMetadata objectMetadata = ossClient.getObjectMetadata(bucketName, objectName);

            // Check whether the object is an Archive object. 
            StorageClass storageClass = objectMetadata.getObjectStorageClass();
            if (storageClass == StorageClass.Archive) {
                // Restore the object. 
                ossClient.restoreObject(bucketName, objectName);

                // Specify the time to wait for the object to be restored. 
                do {
                    Thread.sleep(1000);
                    objectMetadata = ossClient.getObjectMetadata(bucketName, objectName);
                } while (!objectMetadata.isRestoreCompleted());
            }

            // Query the restored object. 
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            ossObject.getObjectContent().close();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}           
import time
import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="restore object sample")
# Add the required command-line arguments.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS.')
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    # Parse the incoming command-line arguments.
    args = parser.parse_args()

    # Load authentication information from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default SDK configurations.
    cfg = oss.config.load_default()
    # Set the credential provider to environment variable-based authentication.
    cfg.credentials_provider = credentials_provider
    # Set the region.
    cfg.region = args.region
    # If an endpoint is provided, set the endpoint as a configuration item.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client.
    client = oss.Client(cfg)

    # Execute the request to restore the object.
    result = client.restore_object(oss.RestoreObjectRequest(
        bucket=args.bucket,
        key=args.key,
        restore_request=oss.RestoreRequest(
            days=1,
            # Optional: Set the restoration priority for Cold Archive or Deep Cold Archive objects. Valid values: Expedited, Standard, and Bulk. Default value: Standard.
            # tier="Bulk",
        )
    ))

    # Print the result of the restore request.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' version id: {result.version_id},'
          f' restore priority: {result.restore_priority},'
    )

    # Loop to check whether the object is restored.
    while True:
        # Get the object header.
        result = client.head_object(oss.HeadObjectRequest(
            bucket=args.bucket,
            key=args.key,
        ))

        # Check the restored state.
        if result.restore and result.restore != 'ongoing-request="true"':
            print('Restore is successful')
            break
        # Check again after 5 seconds.
        time.sleep(5)
        print(result.restore)

# Program entry point.
if __name__ == "__main__":
    main()
const OSS = require('ali-oss')

const client = new OSS({
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the bucket name. For example, examplebucket.
  bucket: 'examplebucket',
});

// Specify the name of the Archive object to restore. For example, exampleobject.txt.
client.restore('exampleobject.txt').then((res) => {
    console.log(res);
}).catch(err => {
    console.log(err);
})
using Aliyun.OSS;
using Aliyun.OSS.Model;
using Aliyun.OSS.Model;
using System.Net;
using System.Text;
using Aliyun.OSS.Common;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. The path cannot contain the bucket name. 
var objectName = "yourObjectName";
// Specify the content of the object. 
var objectContent = "More than just cloud.";
int maxWaitTimeInSeconds = 600;
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Create an Archive bucket. 
    var bucket = client.CreateBucket(bucketName, StorageClass.Archive);
    Console.WriteLine("Create Archive bucket succeeded, {0} ", bucket.Name);
}
catch (Exception ex)
{
    Console.WriteLine("Create Archive bucket failed, {0}", ex.Message);
}
// Upload the object to the bucket and set the storage class of the object to Archive. 
try
{
    byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
    MemoryStream requestContent = new MemoryStream(binaryData);
    client.PutObject(bucketName, objectName, requestContent);
    Console.WriteLine("Put object succeeded, {0}", objectName);
}
catch (Exception ex)
{
    Console.WriteLine("Put object failed, {0}", ex.Message);
}
var metadata = client.GetObjectMetadata(bucketName, objectName);
string storageClass = metadata.HttpMetadata["x-oss-storage-class"] as string;
if (storageClass != "Archive")
{
    Console.WriteLine("StorageClass is {0}", storageClass);
    return;
}
// Restore the Archive object. 
RestoreObjectResult result = client.RestoreObject(bucketName, objectName);
Console.WriteLine("RestoreObject result HttpStatusCode : {0}", result.HttpStatusCode);
if (result.HttpStatusCode != HttpStatusCode.Accepted)
{
    throw new OssException(result.RequestId + ", " + result.HttpStatusCode + " ,");
}
while (maxWaitTimeInSeconds > 0)
{
    var meta = client.GetObjectMetadata(bucketName, objectName);
    string restoreStatus = meta.HttpMetadata["x-oss-restore"] as string;
    if (restoreStatus != null && restoreStatus.StartsWith("ongoing-request=\"false\"", StringComparison.InvariantCultureIgnoreCase))
    {
        break;
    }
    Thread.Sleep(1000);
    // The maximum wait time decreases by 1 second. 
    maxWaitTimeInSeconds--;
}
if (maxWaitTimeInSeconds == 0)
{
    Console.WriteLine("RestoreObject is timeout. ");
    throw new TimeoutException();
}
else
{
    Console.WriteLine("RestoreObject is successful. ");
}
// Restore the object.
RestoreObjectRequest restore = new RestoreObjectRequest();
// Specify the bucket name. Example: examplebucket.
restore.setBucketName("examplebucket");
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.txt.
restore.setObjectKey("exampleobject.txt");
OSSAsyncTask task = oss.asyncRestoreObject(restore, new OSSCompletedCallback<RestoreObjectRequest,
        RestoreObjectResult>() {
    @Override
    public void onSuccess(RestoreObjectRequest request, RestoreObjectResult result) {
        Log.i("info", "code::"+result.getStatusCode());

    }

    @Override
    public void onFailure(RestoreObjectRequest request, ClientException clientException,
                          ServiceException serviceException) {
        Log.e("errorMessage", "error: "+serviceException.getRawMessage());

    }
});

task.waitUntilFinished();
OSSRestoreObjectRequest *request = [OSSRestoreObjectRequest new];
// Bucket containing the archived object
request.bucketName = @"examplebucket";
// Full path of the object (do not include the bucket name)
request.objectKey = @"exampleobject.txt";

OSSTask *restoreObjectTask = [client restoreObject:request];
[restoreObjectTask continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
    if (!task.error) {
        NSLog(@"Restore request submitted successfully");
        // Note: The object is not immediately accessible.
        // Check restoration status before attempting to read.
    } else {
        NSLog(@"Restore request failed: %@", task.error);
        // Handle specific errors (see Error handling section)
    }
    return nil;
}];
// Use synchronous blocking if you need to wait for request submission to complete
// Not recommended for UI thread as it blocks execution
// [restoreObjectTask waitUntilFinished];
#include <alibabacloud/oss/OssClient.h>
#include <thread>
#include <chrono>
#include <algorithm>

using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize OSS account information. */
    
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, for the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, for the China (Hangzhou) region, set the Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Set BucketName to the name of your bucket, for example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* Set ObjectName to the full path of the Archive object. The path does not include the bucket name. */
    std::string ObjectName = "yourObjectName";
  
    /* Initialize network resources. */
    InitializeSdk();
    
    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
  
    /* Restore the Archive object. */
    auto outcome = client.RestoreObject(BucketName, ObjectName);
    /* Objects that are not in the Archive storage class cannot be restored. */
    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "RestoreObject fail, code: " << outcome.error().Code() <<
        ", message: " << outcome.error().Message() <<
        ", requestId: " << outcome.error().RequestId() << std::endl;
        return -1;
    }
    std::string onGoingRestore("ongoing-request=\"false\"");
    int maxWaitTimeInSeconds = 600;
    while (maxWaitTimeInSeconds > 0)
    {
        auto meta = client.HeadObject(BucketName, ObjectName);
        std::string restoreStatus = meta.result().HttpMetaData()["x-oss-restore"];
        std::transform(restoreStatus.begin(), restoreStatus.end(), restoreStatus.begin(), ::tolower);
        if (!restoreStatus.empty() && 
        restoreStatus.compare(0, onGoingRestore.size(), onGoingRestore)==0) {
            std::cout << " success, restore status:" << restoreStatus << std::endl;
            /* The Archive object is successfully restored. */
            break;
        }
        std::cout << " info, WaitTime:" << maxWaitTimeInSeconds
        << "; restore status:" << restoreStatus << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(10));
        maxWaitTimeInSeconds--;     
    }
    if (maxWaitTimeInSeconds == 0)
    {
        std::cout << "RestoreObject fail, TimeoutException" << std::endl;
    }
    /* Release network resources. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the bucket name. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Initialize the aos_string_t type with a char* string. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    // Configure the following two parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether a CNAME is used. 0 indicates that no CNAME is used. */
    options->config->is_cname = 0;
    /* Set network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method at the program entry to initialize global resources such as the network and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* A memory pool for memory management. This is equivalent to apr_pool_t. The implementation code is in the apr library. */
    aos_pool_t *pool;
    /* Create a memory pool. The second parameter is NULL, which indicates that the new memory pool does not inherit from another memory pool. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter contains global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate memory to options in the memory pool. */  
    oss_client_options = oss_request_options_create(pool);
    /* Initialize the client options oss_client_options. */
    init_options(oss_client_options);
    /* Initialize parameters. */
    aos_string_t bucket;
    aos_string_t object;   
    aos_table_t *headers = NULL;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    headers = aos_table_make(pool, 0);
       
    /* Restore the object. */
    do {
        headers = aos_table_make(pool, 0);
        resp_status = oss_restore_object(oss_client_options, &bucket, &object, headers, &resp_headers);
        printf("restore object resp_status->code: %d \n", resp_status->code);
        if (resp_status->code != 409) {
            break;
        } else {
            printf("restore object is already in progress, resp_status->code: %d \n", resp_status->code);
            apr_sleep(5000);
        }
    } while (1);
    /* Release the memory pool. This releases the memory allocated to resources during the request. */
    aos_pool_destroy(pool);
    /* Release the previously allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}
package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables for command-line arguments.
var (
	region     string // The OSS region.
	bucketName string // The bucket name.
	objectName string // The object name.
)

// init initializes the command-line flags.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command-line flags.
	flag.Parse()

	// Check if the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check if the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check if the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configuration, and set the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to restore the object.
	request := &oss.RestoreObjectRequest{
		Bucket: oss.Ptr(bucketName), // The bucket name.
		Key:    oss.Ptr(objectName), // The object name.
		RestoreRequest: &oss.RestoreRequest{
			Days: 3, // Set the restoration period to 3 days.
		},
	}

	// Send the request to restore the object.
	result, err := client.RestoreObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to restore object %v", err)
	}

	// Print the result.
	log.Printf("restore object result:%#v\n", result)
}
<?php

// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define and describe command-line parameters.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint for accessing OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];

// Convert the descriptions to a list of long options required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command-line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing.
    }
}

// Assign the values parsed from the command-line parameters to the corresponding variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"];       // The name of the object.

// Load access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Create a RestoreObjectRequest object to restore the Archive object.
$request = new Oss\Models\RestoreObjectRequest(bucket: $bucket, key: $key);

// Restore the object.
$result = $client->restoreObject($request);

// Display the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request succeeded.
    'request id:' . $result->requestId . PHP_EOL     // The request ID, which can be used to debug or trace the request.
);

ossutil

ossutil é uma ferramenta CLI para gerenciar o OSS, adequada para restaurações via script e em lote.

Restore Archive objects

  • Restaure um objeto Archive chamado exampleobject.txt no bucket examplebucket:

    ossutil restore oss://examplebucket/exampleobject.txt
  • Restaure um objeto Archive e defina o período de validade da réplica como 3 dias:

    ossutil restore oss://examplebucket/exampleobject.txt --days 3
  • Restaure objetos a partir de uma lista.

    Nota

    Cada linha deve ser um caminho OSS no formato oss://{bucket}/{key}.

    Exemplo de list.txt:

    oss://examplebucket/key1
    oss://examplebucket/key2
    ossutil restore list://list.txt
  • Restaure objetos a partir de uma lista sem verificar o status dos objetos:

    ossutil restore list://list.txt --no-check-status 
  • Restaure objetos a partir de um arquivo de inventário.

    Nota

    A configuração de inventário gera um arquivo csv.gz e um arquivo manifest.json, ambos necessários para esta operação.

    ossutil restore list://ca8007fc-4123-493e-9a01-dd1511fbac54.csv.gz --list-format inventory --list-manifest-from manifest.json
  • Restaure objetos a partir de um arquivo de inventário sem verificar o status dos objetos:

    ossutil restore list://ca8007fc-4123-493e-9a01-dd1511fbac54.csv.gz --list-format inventory --list-manifest-from manifest.json --no-check-status

Restore Cold Archive objects

Restaure um objeto Cold Archive e defina o período de validade da réplica como 5 dias:

ossutil restore oss://examplebucket/exampleobject.txt --tier Bulk --days 5

Restore Deep Cold Archive objects

Restaure um objeto Deep Cold Archive e defina o período de validade da réplica como 10 dias:

ossutil restore oss://examplebucket/exampleobject.txt --tier Standard --days 10

Para mais informações, consulte restore (Restore objects).

ossbrowser

O ossbrowser oferece suporte a operações no nível do bucket, semelhantes ao console. Siga a interface do ossbrowser para restaurar objetos. Para mais informações, consulte 常用操作.

API

Para requisitos altamente personalizados, envie solicitações REST API diretamente. Você precisa escrever o código para calcular as assinaturas. Para mais informações, consulte RestoreObject.

Faturamento

Item faturável

Descrição

Classes de armazenamento aplicáveis

Data retrieval fee

Taxa única baseada no volume de dados restaurados (GB). Este é o principal custo da restauração.

Archive, Cold Archive e Deep Cold Archive

Request fee

Cobrado por cada solicitação RestoreObject.

Archive (cobrado como solicitações Put), Cold Archive e Deep Cold Archive (cobrados como solicitações de recuperação)

Storage fee

As taxas de armazenamento incidem durante e após a restauração, com base na classe de armazenamento.

Archive, Cold Archive e Deep Cold Archive

Temporary storage fee

A réplica temporária consome espaço de armazenamento. A cobrança é diária durante todo o período de validade da réplica.

Cold Archive e Deep Cold Archive

Cotas e limites

  • Para uma única conta Alibaba Cloud em uma única região, a cota de restauração de referência para objetos Cold Archive é de 500 objetos por segundo em média. A cota total de restauração para as três prioridades é de 100 TB a 120 TB por dia.Caso seu negócio exija cotas de restauração maiores, entre em contato com o Technical Support.

  • Para uma única conta Alibaba Cloud em uma única região, a cota de restauração de referência para objetos Deep Cold Archive é de 100 objetos por segundo em média. A cota total de restauração para as duas prioridades é de 10 TB a 15 TB por dia.Caso seu negócio exija cotas de restauração maiores, entre em contato com o Technical Support.

Nota

Se a cota for excedida, ainda é possível enviar solicitações de restauração. As solicitações são enfileiradas e podem levar mais tempo do que o definido pela prioridade especificada.

FAQ