Nem todos os dados enviados aos buckets do Object Storage Service (OSS) são acessados com frequência. Dados raramente acessados são armazenados em armazenamento frio para fins de conformidade e arquivamento. Para excluir dados armazenados em vários buckets do OSS simultaneamente, configure regras de ciclo de vida com base na última modificação dos dados. Recomendamos armazenar dados frios e quentes separadamente para reduzir custos. Para isso, configure o OSS para monitorar automaticamente os padrões de acesso, identificar dados frios e alterar a classe de armazenamento correspondente. Nesse cenário, também é possível configurar regras de ciclo de vida com base no último acesso aos dados.
Observações de uso
Antes de configurar regras de ciclo de vida baseadas na última modificação ou no último acesso dos objetos, familiarize-se com esse recurso. Para mais informações, consulte Regras de ciclo de vida baseadas na última modificação e Regras de ciclo de vida baseadas no último acesso.
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre as regiões e endpoints compatíveis, consulte Regiões e endpoints.
As credenciais de acesso neste tópico são obtidas de variáveis de ambiente. Para mais informações, consulte Configurar credenciais de acesso.
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configuração do cliente.
A configuração de regras de ciclo de vida exige a permissão
oss:PutBucketLifecycle. A consulta requer a permissãooss:GetBucketLifecycle, enquanto a limpeza das regras exige a permissãooss:DeleteBucketLifecycle. Para mais informações, consulte Conceder uma política personalizada.
Configure regras de ciclo de vida
O código a seguir apresenta exemplos de duas regras de ciclo de vida: uma baseada na última modificação dos dados e outra no último acesso. Após a configuração, modifique as regras conforme as necessidades do seu negócio. Para saber como modificar regras existentes, consulte Modificar regras de ciclo de vida.
Configure uma regra de ciclo de vida baseada na última modificação que corresponda a objetos com tag e prefixo de nome específicos
O exemplo abaixo mostra como configurar uma regra de ciclo de vida baseada na última modificação para um bucket chamado examplebucket. A regra corresponde a objetos por prefixo e tag. As classes de armazenamento dos objetos correspondentes são alteradas ou os objetos são excluídos de acordo com a regra definida.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.model.LifecycleRule;
import com.aliyun.oss.model.SetBucketLifecycleRequest;
import com.aliyun.oss.model.StorageClass;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 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 {
// Create a request by using SetBucketLifecycleRequest.
SetBucketLifecycleRequest request = new SetBucketLifecycleRequest(bucketName);
// Specify the ID of the lifecycle rule.
String ruleId0 = "rule0";
// Specify the prefix that you want the lifecycle rule to match.
String matchPrefix0 = "A0/";
// Specify the tag that you want the lifecycle rule to match.
Map<String, String> matchTags0 = new HashMap<String, String>();
// Specify the key and value of the tag. In the example, the key is set to owner and the value is set to John.
matchTags0.put("owner", "John");
String ruleId1 = "rule1";
String matchPrefix1 = "A1/";
Map<String, String> matchTags1 = new HashMap<String, String>();
matchTags1.put("type", "document");
String ruleId2 = "rule2";
String matchPrefix2 = "A2/";
String ruleId3 = "rule3";
String matchPrefix3 = "A3/";
String ruleId4 = "rule4";
String matchPrefix4 = "A4/";
String ruleId5 = "rule5";
String matchPrefix5 = "A5/";
String ruleId6 = "rule6";
String matchPrefix6 = "A6/";
// Set the expiration time to three days after the last modified time.
LifecycleRule rule = new LifecycleRule(ruleId0, matchPrefix0, LifecycleRule.RuleStatus.Enabled, 3);
rule.setTags(matchTags0);
request.AddLifecycleRule(rule);
// Specify that objects that are created before the specified date expire.
rule = new LifecycleRule(ruleId1, matchPrefix1, LifecycleRule.RuleStatus.Enabled);
rule.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
rule.setTags(matchTags1);
request.AddLifecycleRule(rule);
// Specify that parts expire three days after they are last modified.
rule = new LifecycleRule(ruleId2, matchPrefix2, LifecycleRule.RuleStatus.Enabled);
LifecycleRule.AbortMultipartUpload abortMultipartUpload = new LifecycleRule.AbortMultipartUpload();
abortMultipartUpload.setExpirationDays(3);
rule.setAbortMultipartUpload(abortMultipartUpload);
request.AddLifecycleRule(rule);
// Specify that parts that are created before the specific date expire.
rule = new LifecycleRule(ruleId3, matchPrefix3, LifecycleRule.RuleStatus.Enabled);
abortMultipartUpload = new LifecycleRule.AbortMultipartUpload();
abortMultipartUpload.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
rule.setAbortMultipartUpload(abortMultipartUpload);
request.AddLifecycleRule(rule);
// Specify that the storage classes of objects are changed to IA 10 days after they are last modified, and to Archive 30 days after they are last modified.
rule = new LifecycleRule(ruleId4, matchPrefix4, LifecycleRule.RuleStatus.Enabled);
List<LifecycleRule.StorageTransition> storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
LifecycleRule.StorageTransition storageTransition = new LifecycleRule.StorageTransition();
storageTransition.setStorageClass(StorageClass.IA);
storageTransition.setExpirationDays(10);
storageTransitions.add(storageTransition);
storageTransition = new LifecycleRule.StorageTransition();
storageTransition.setStorageClass(StorageClass.Archive);
storageTransition.setExpirationDays(30);
storageTransitions.add(storageTransition);
rule.setStorageTransition(storageTransitions);
request.AddLifecycleRule(rule);
// Specify that the storage classes of objects that are last modified before October 12, 2022 are changed to Archive.
rule = new LifecycleRule(ruleId5, matchPrefix5, LifecycleRule.RuleStatus.Enabled);
storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
storageTransition = new LifecycleRule.StorageTransition();
storageTransition.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
storageTransition.setStorageClass(StorageClass.Archive);
storageTransitions.add(storageTransition);
rule.setStorageTransition(storageTransitions);
request.AddLifecycleRule(rule);
// Specify that rule6 is configured for versioning-enabled buckets.
rule = new LifecycleRule(ruleId6, matchPrefix6, LifecycleRule.RuleStatus.Enabled);
// Specify that the storage classes of objects are changed to Archive 365 days after the objects are last modified.
storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
storageTransition = new LifecycleRule.StorageTransition();
storageTransition.setStorageClass(StorageClass.Archive);
storageTransition.setExpirationDays(365);
storageTransitions.add(storageTransition);
rule.setStorageTransition(storageTransitions);
// Configure the lifecycle rule to automatically delete expired delete markers.
rule.setExpiredDeleteMarker(true);
// Specify that the storage classes of the previous versions of objects are changed to IA 10 days after the objects are last modified.
LifecycleRule.NoncurrentVersionStorageTransition noncurrentVersionStorageTransition =
new LifecycleRule.NoncurrentVersionStorageTransition().withNoncurrentDays(10).withStrorageClass(StorageClass.IA);
// Specify that the storage classes of the previous versions of objects are changed to Archive 20 days after the objects are last modified.
LifecycleRule.NoncurrentVersionStorageTransition noncurrentVersionStorageTransition2 =
new LifecycleRule.NoncurrentVersionStorageTransition().withNoncurrentDays(20).withStrorageClass(StorageClass.Archive);
// Specify that the previous versions of objects are deleted 30 days after the objects are last modified.
LifecycleRule.NoncurrentVersionExpiration noncurrentVersionExpiration = new LifecycleRule.NoncurrentVersionExpiration().withNoncurrentDays(30);
List<LifecycleRule.NoncurrentVersionStorageTransition> noncurrentVersionStorageTransitions = new ArrayList<LifecycleRule.NoncurrentVersionStorageTransition>();
noncurrentVersionStorageTransitions.add(noncurrentVersionStorageTransition2);
rule.setStorageTransition(storageTransitions);
rule.setNoncurrentVersionExpiration(noncurrentVersionExpiration);
rule.setNoncurrentVersionStorageTransitions(noncurrentVersionStorageTransitions);
request.AddLifecycleRule(rule);
// Initiate a request to configure lifecycle rules.
ossClient.setBucketLifecycle(request);
// Query the lifecycle rules that are configured for the bucket.
List<LifecycleRule> listRules = ossClient.getBucketLifecycle(bucketName);
for(LifecycleRule rules : listRules){
System.out.println("ruleId="+rules.getId()+", matchPrefix="+rules.getPrefix());
}
} 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();
}
}
}
}
Configure uma regra de ciclo de vida baseada na última modificação que corresponda a objetos sem a tag ou prefixo de nome específicos
O código a seguir exemplifica como configurar uma regra de ciclo de vida baseada na última modificação. Essa regra altera a classe de armazenamento de objetos no bucket examplebucket para IA 30 dias após a última modificação, desde que atendam às seguintes condições: os nomes dos objetos não contêm o prefixo log e os objetos não possuem a tag com chave tag1 e valor value1. Essas condições são especificadas no elemento Not do nó de filtro.
Somente o OSS SDK for Java 3.16.0 e versões posteriores oferecem suporte ao elemento NOT.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.ArrayList;
import java.util.List;
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 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 {
String ruleId = "mtime transition1";
String matchPrefix = "logs";
SetBucketLifecycleRequest request = new SetBucketLifecycleRequest(bucketName);
LifecycleFilter filter = new LifecycleFilter();
LifecycleNot not = new LifecycleNot();
Tag tag = new Tag("key1","value1");
not.setPrefix("logs/not-prefix");
not.setTag(tag);
List<LifecycleNot> notList = new ArrayList<LifecycleNot>();
notList.add(not);
filter.setNotList(notList);
List<LifecycleRule.StorageTransition> storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
LifecycleRule.StorageTransition storageTransition = new LifecycleRule.StorageTransition();
storageTransition.setStorageClass(StorageClass.IA);
storageTransition.setExpirationDays(30);
storageTransitions.add(storageTransition);
LifecycleRule rule = new LifecycleRule(ruleId, matchPrefix, LifecycleRule.RuleStatus.Enabled);
rule.setFilter(filter);
rule.setStorageTransition(storageTransitions);
request.AddLifecycleRule(rule);
VoidResult result = ossClient.setBucketLifecycle(request);
System.out.println("Returned status code:"+result.getResponse().getStatusCode()+" set lifecycle succeed");
} 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();
}
}
}
}
Configure uma regra de ciclo de vida baseada no último acesso para alterar as classes de armazenamento dos objetos
O exemplo a seguir demonstra como configurar uma regra de ciclo de vida baseada no último acesso para alterar as classes de armazenamento dos objetos no bucket examplebucket:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.ArrayList;
import java.util.List;
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 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 {
ossClient.putBucketAccessMonitor(bucketName, AccessMonitor.AccessMonitorStatus.Enabled.toString());
// Create a lifecycle rule and set the ID to rule1. Specify that the storage classes of objects whose names contain the logs prefix and whose size is less than or equal to 64 KB are changed to IA 30 days after the objects are last accessed. In addition, specify that the objects whose name contain the logs prefix are still stored as IA objects when the objects are accessed again.
LifecycleRule lifecycleRule = new LifecycleRule("rule1", "logs", LifecycleRule.RuleStatus.Enabled);
List<LifecycleRule> lifecycleRuleList = new ArrayList<LifecycleRule>();
SetBucketLifecycleRequest setBucketLifecycleRequest = new SetBucketLifecycleRequest(bucketName);
LifecycleRule.StorageTransition storageTransition = new LifecycleRule.StorageTransition();
storageTransition.setStorageClass(StorageClass.IA);
storageTransition.setExpirationDays(30);
storageTransition.setIsAccessTime(true);
storageTransition.setReturnToStdWhenVisit(false);
storageTransition.setAllowSmallFile(true);
List<LifecycleRule.StorageTransition> storageTransitionList = new ArrayList<LifecycleRule.StorageTransition>();
storageTransitionList.add(storageTransition);
lifecycleRule.setStorageTransition(storageTransitionList);
lifecycleRuleList.add(lifecycleRule);
// Create a lifecycle rule and set the ID to rule2. Specify that the previous versions of the objects whose names contain the dir prefix and whose size is greater than 64 KB are changed to IA 10 days after the objects are last accessed. In addition, specify that the storage classes of the objects whose names contain the dir prefix are changed to Standard when the objects are accessed again.
LifecycleRule lifecycleRule2 = new LifecycleRule("rule2", "dir", LifecycleRule.RuleStatus.Enabled);
LifecycleRule.NoncurrentVersionStorageTransition noncurrentVersionStorageTransition = new LifecycleRule.NoncurrentVersionStorageTransition();
noncurrentVersionStorageTransition.setStorageClass(StorageClass.IA);
noncurrentVersionStorageTransition.setNoncurrentDays(10);
noncurrentVersionStorageTransition.setIsAccessTime(true);
noncurrentVersionStorageTransition.setReturnToStdWhenVisit(true);
noncurrentVersionStorageTransition.setAllowSmallFile(false);
List<LifecycleRule.NoncurrentVersionStorageTransition> noncurrentVersionStorageTransitionList = new ArrayList<LifecycleRule.NoncurrentVersionStorageTransition>();
noncurrentVersionStorageTransitionList.add(noncurrentVersionStorageTransition);
lifecycleRule2.setNoncurrentVersionStorageTransitions(noncurrentVersionStorageTransitionList);
lifecycleRuleList.add(lifecycleRule2);
setBucketLifecycleRequest.setLifecycleRules(lifecycleRuleList);
// Configure the lifecycle rules.
ossClient.setBucketLifecycle(setBucketLifecycleRequest);
} 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();
}
}
}
}
Visualize regras de ciclo de vida
O código abaixo mostra como consultar as regras de ciclo de vida configuradas para o bucket chamado examplebucket:
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.LifecycleRule;
import java.util.List;
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 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 {
// Query the lifecycle rules of the bucket.
List<LifecycleRule> rules = ossClient.getBucketLifecycle(bucketName);
// Query the lifecycle rules that are configured for the bucket.
for (LifecycleRule r : rules) {
System.out.println("================");
// View the rule ID.
System.out.println("rule id: " + r.getId());
// View the status of the rule.
System.out.println("rule status: " + r.getStatus());
// View the prefix configured in the lifecycle rule.
System.out.println("rule prefix: " + r.getPrefix());
// View the tag configured in the lifecycle rule.
if (r.hasTags()) {
System.out.println("rule tagging: "+ r.getTags().toString());
}
// View the validity period configured in the lifecycle rule.
if (r.hasExpirationDays()) {
System.out.println("rule expiration days: " + r.getExpirationDays());
}
// View the expiration date configured in the lifecycle rule.
if (r.hasCreatedBeforeDate()) {
System.out.println("rule expiration create before days: " + r.getCreatedBeforeDate());
}
// View the rule for expired parts.
if(r.hasAbortMultipartUpload()) {
if(r.getAbortMultipartUpload().hasExpirationDays()) {
System.out.println("rule abort uppart days: " + r.getAbortMultipartUpload().getExpirationDays());
}
if (r.getAbortMultipartUpload().hasCreatedBeforeDate()) {
System.out.println("rule abort uppart create before date: " + r.getAbortMultipartUpload().getCreatedBeforeDate());
}
}
// View the rule of storage class change.
if (r.getStorageTransition().size() > 0) {
for (LifecycleRule.StorageTransition transition : r.getStorageTransition()) {
if (transition.hasExpirationDays()) {
System.out.println("rule storage trans days: " + transition.getExpirationDays() +
" trans storage class: " + transition.getStorageClass());
}
if (transition.hasCreatedBeforeDate()) {
System.out.println("rule storage trans before create date: " + transition.getCreatedBeforeDate());
}
// Check whether lifecycle rules are configured based on the last access time. This configuration applies only to OSS SDK for Java 3.16.0 and later.
System.out.println("StorageTransition IsAccessTime: "+transition.getIsAccessTime());
// View the lifecycle rule to check whether the storage class of the object is changed to Standard when the object is accessed again after the storage class of the object is changed to IA. This configuration applies only to OSS SDK for Java 3.16.0 and later.
System.out.println("StorageTransition ReturnToStdWhenVisit: "+transition.getReturnToStdWhenVisit());
}
}
// View the lifecycle rule to check whether expired delete markers are automatically deleted.
if (r.hasExpiredDeleteMarker()) {
System.out.println("rule expired delete marker: " + r.getExpiredDeleteMarker());
}
// View the configurations used to change the storage classes of previous versions of the objects.
if (r.hasNoncurrentVersionStorageTransitions()) {
for (LifecycleRule.NoncurrentVersionStorageTransition transition : r.getNoncurrentVersionStorageTransitions()) {
System.out.println("rule noncurrent versions trans days:" + transition.getNoncurrentDays() +
" trans storage class: " + transition.getStorageClass());
// View the access time of objects. This configuration applies only to OSS SDK for Java 3.16.0 and later.
System.out.println("NoncurrentVersionStorageTransition IsAccessTime: "+transition.getIsAccessTime());
// View the ReturnToStdWhenVisit. This configuration applies only to OSS SDK for Java 3.16.0 and later.
System.out.println("NoncurrentVersionStorageTransition ReturnToStdWhenVisit: "+transition.getReturnToStdWhenVisit());
}
}
// View the expiration rule for previous versions of objects.
if (r.hasNoncurrentVersionExpiration()) {
System.out.println("rule noncurrent versions expiration days:" + r.getNoncurrentVersionExpiration().getNoncurrentDays());
}
}
} 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();
}
}
}
}
Exclua regras de ciclo de vida
O exemplo a seguir ilustra como limpar as regras de ciclo de vida em um bucket chamado examplebucket. Para excluir apenas uma ou mais regras específicas, consulte Excluir regras de ciclo de vida.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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 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 {
ossClient.deleteBucketLifecycle(bucketName);
} 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();
}
}
}
}
Referências
Para acessar o código de exemplo completo sobre regras de ciclo de vida, visite o GitHub.
Para mais detalhes sobre a operação de API usada para configurar uma regra de ciclo de vida, consulte PutBucketLifecycle.
Sobre a operação de API para consultar regras de ciclo de vida, consulte GetBucketLifecycle.
Quanto à operação de API para excluir regras de ciclo de vida, consulte DeleteBucketLifecycle.