Todos los productos
Search
Centro de documentos

Object Storage Service:Restaurar objetos (OSS SDK for Java 1.0)

Última actualización: Sep 03, 2026

Si no habilita el acceso en tiempo real a los objetos Archive, solo podrá acceder a ellos después de restaurarlos. Los objetos Cold Archive y Deep Cold Archive no admiten el acceso en tiempo real; por lo tanto, debe restaurarlos antes de consultarlos. Por lo general, la restauración de un objeto Archive toma varios minutos, la de un objeto Cold Archive requiere varias horas y la de un objeto Deep Cold Archive tarda entre 12 y 48 horas. Estos tiempos son solo una referencia y pueden variar según el escenario real. Este tema describe cómo restaurar objetos Archive, Cold Archive y Deep Cold Archive.

Notas de uso

  • La operación RestoreObject solo se puede invocar en objetos Archive, Cold Archive y Deep Cold Archive.

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Para acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints compatibles, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información, consulte 配置访问凭证.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como usar un dominio personalizado o autenticarse mediante credenciales de Security Token Service (STS), consulte Client configuration.

  • Para restaurar un objeto, debe contar con el permiso oss:RestoreObject. Para obtener más información, consulte Grant a custom policy.

Restaurar un objeto Archive

A continuación se muestra un ejemplo de código para restaurar un objeto Archive:

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();
            }
        }
    }
}           

Restaurar un objeto Cold Archive

El siguiente fragmento de código ilustra el proceso para restaurar un objeto Cold Archive:

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 Cold 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 {                    
            // Specify the restoration mode of the Cold Archive object. 
            // RestoreTier.RESTORE_TIER_EXPEDITED specifies that the object is restored within 1 hour. 
            // RestoreTier.RESTORE_TIER_STANDARD specifies that the object is restored within 2 to 5 hours. 
            // RestoreTier.RESTORE_TIER_BULK specifies that the object is restored within 5 to 12 hours. 
           RestoreJobParameters jobParameters = new RestoreJobParameters(RestoreTier.RESTORE_TIER_BULK);

            // Configure parameters. For example, set the restoration mode of the object to Standard, and set the duration for which the object remains in the restored state to 2 days. 
            // The first parameter specifies the duration (days) for which the object remains in the restored state. The default value is 1. This parameter takes effect for Archive and Cold Archive objects. 
            // jobParameters specifies the restoration mode of the object and takes effect only for Cold Archive objects. 
            RestoreConfiguration configuration = new RestoreConfiguration(2, jobParameters);

            // Initiate an object restoration request. 
            ossClient.restoreObject(bucketName, objectName, configuration);
        } 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();
            }
        }
    }
}

Restaurar un objeto Deep Cold Archive

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 Deep Cold 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 {          
            // Configure the restoration mode. In this example, the restoration mode is RESTORE_TIER_STANDARD. 
            // RestoreTier.RESTORE_TIER_EXPEDITED specifies that the object is restored within 12 hours.             
            // RestoreTier.RESTORE_TIER_STANDARD specifies that the object is restored within 48 hours. 
            RestoreJobParameters jobParameters = new RestoreJobParameters(RestoreTier.RESTORE_TIER_STANDARD);

            // Specify the duration (days) for which the object remains in the restored state. The default value is 1. In this example, the validity period is 2 days. 
            RestoreConfiguration configuration = new RestoreConfiguration(2, jobParameters);

            // Initiate an object restoration request. 
            ossClient.restoreObject(bucketName, objectName, configuration);
        } 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();
            }
        }
    }
}

Referencias

  • Para consultar el código de ejemplo completo utilizado para restaurar objetos, visite GitHub.

  • Para obtener más información sobre la operación de API que permite restaurar objetos, consulte RestoreObject.