CloudBox üzerindeki Object Storage Service (OSS), yerel verilerinizi izlemenize ve işlemenize olanak tanır. Düşük gecikme süresi gerektiren veya birden fazla şube ofisinin tek bir merkezden yönetilmesini isteyen kullanım durumları için idealdir. Bu konuda, paket oluşturma, nesne yükleme ve nesne indirme gibi CloudBox üzerindeki OSS'in temel işlemleri açıklanmaktadır.
Ön koşullar
CloudBox üzerindeki OSS hizmeti yalnızca China (Hangzhou), China (Shanghai), China (Shenzhen), China (Heyuan), China (Beijing) ve China (Chengdu) bölgelerinde kullanılabilir.
CloudBox için bir VPC ve vSwitch oluşturdunuz.
CloudBox VPC'niz için SingleTunnel ağ türü talep etmek üzere teknik destek ile iletişime geçtiniz.
1. Adım: Paket oluşturun
OSS konsolunu kullanın
OSS konsolunda oturum açın.
Sol gezinme bölmesinde Data Service > OSS on CloudBox Buckets seçeneklerini belirleyin ve sol üst köşede bulunan Create Bucket düğmesine tıklayın.
-
Create Bucket sayfasında bir paket adı girin, varsayılan ayarları kabul edin ve OK düğmesine tıklayın.
Paket adı aşağıdaki gereksinimleri karşılamalıdır:
Paket adı, CloudBox içinde benzersiz olmalıdır.
Ad yalnızca küçük harfler, rakamlar ve tire (-) içerebilir.
Ad küçük bir harf veya rakamla başlamalı ve bitmelidir.
Ad 3 ila 63 karakter uzunluğunda olmalıdır.
Alibaba Cloud SDK kullanın
Java, Python veya Go için OSS SDK'yı kullanarak (Java SDK 3.15.0 veya sonrası, Python SDK V2 1.1.1 veya sonrası, Go SDK V2 v1.2.1 veya sonrası) CloudBox üzerinde bir OSS paketi oluşturabilirsiniz. CloudBox üzerindeki OSS için Python ve Go SDK'ları, genel cloud OSS ile aynı şekilde çağrılır. İstemci oluşturma hakkında bilgi için SDK desteği konusuna bakın.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
public class Demo {
public static void main(String[] args) throws Exception {
// Specify the data endpoint for the OSS on CloudBox bucket.
String endpoint = "https://cb-f8z7yvzgwfkl9q0h****.cn-hangzhou.oss-cloudbox.aliyuncs.com";
// 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.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the OSS on CloudBox bucket, for example, examplebucket.
String bucketName = "examplebucket";
// Specify the region where the OSS on CloudBox bucket is located.
String region = "cn-hangzhou";
// Specify the Cloud Box ID.
String cloudBoxId = "cb-f8z7yvzgwfkl9q0h****";
// Create an OSSClient instance.
// Call shutdown() to release resources when the client is no longer needed.
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
conf.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(new DefaultCredentialProvider(credentialsProvider.getCredentials()))
.clientConfiguration(conf)
.region(region)
.cloudBoxId(cloudBoxId)
.build();
try {
// Create a CreateBucketRequest object.
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
// Set the ACL of the OSS on CloudBox bucket to public-read. The default ACL is private.
//createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
// Create the OSS on CloudBox bucket.
ossClient.createBucket(createBucketRequest);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request reached OSS but was rejected with an error response.");
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 a 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 alibabacloud_oss_v2 as oss
# Obtain access credentials from environment variables. Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables before you run the code.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# The region where the CloudBox is located. For example, cn-hangzhou.
cfg.region = "cn-hangzhou"
# The CloudBox data domain name, in the format CloudboxId.Region.oss-cloudbox.aliyuncs.com.
cfg.endpoint = "cb-xxxx.cn-hangzhou.oss-cloudbox.aliyuncs.com"
# The CloudBox ID.
cfg.cloud_box_id = "cb-xxxx"
client = oss.Client(cfg)
# Create a bucket. The bucket name must be globally unique.
result = client.put_bucket(oss.PutBucketRequest(
bucket="examplebucket",
acl="private",
))
print(f"status code: {result.status_code}, request id: {result.request_id}")package main
import (
"context"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// The region where the CloudBox is located. For example, cn-hangzhou.
region := "cn-hangzhou"
// Obtain access credentials from environment variables. Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables before you run the code.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region).
// The CloudBox data domain name, in the format CloudboxId.Region.oss-cloudbox.aliyuncs.com.
WithEndpoint("cb-xxxx.cn-hangzhou.oss-cloudbox.aliyuncs.com").
// The CloudBox ID.
WithCloudBoxId("cb-xxxx")
client := oss.NewClient(cfg)
// Create a bucket. The bucket name must be globally unique.
result, err := client.PutBucket(context.TODO(), &oss.PutBucketRequest{
Bucket: oss.Ptr("examplebucket"),
})
if err != nil {
log.Fatalf("failed to put bucket %v", err)
}
log.Printf("put bucket result:%#v\n", result)
}ossutil kullanın
ossutil ile CloudBox üzerinde bir OSS paketi oluşturmak için put-bucket komutuna bakın.
REST API kullanın
Uygulamanız geniş kapsamlı özelleştirme gerektiriyorsa REST API'yi doğrudan çağırabilirsiniz. Bu işlem, imzayı manuel olarak hesaplamak için kod yazmanızı gerektirir. Daha fazla bilgi için PutBucket API referansına bakın.
2. Adım: Nesne yükleyin
Alibaba Cloud SDK kullanın
Java, Python veya Go için OSS SDK'yı kullanarak (Java SDK 3.15.0 veya sonrası, Python SDK V2 1.1.1 veya sonrası, Go SDK V2 v1.2.1 veya sonrası) yerel dosyaları CloudBox üzerindeki bir OSS paketine yükleyebilirsiniz. CloudBox üzerindeki OSS için Python ve Go SDK'ları, genel cloud OSS ile aynı şekilde çağrılır. İstemci oluşturma hakkında bilgi için SDK desteği konusuna bakın.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import java.io.File;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
public class Demo {
public static void main(String[] args) throws Exception {
// Specify the data endpoint of the OSS on CloudBox bucket.
String endpoint = "https://cb-f8z7yvzgwfkl9q0h****.cn-hangzhou.oss-cloudbox.aliyuncs.com";
// 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 configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the OSS on CloudBox bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the region where the OSS on CloudBox bucket is located.
String region = "cn-hangzhou";
// Specify the ID of the CloudBox.
String cloudBoxId = "cb-f8z7yvzgwfkl9q0h****";
// Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
String objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt.
// If you do not specify a local path, the file is uploaded from the local path of the project to which the sample program belongs.
String filePath= "D:\\localpath\\examplefile.txt";
// Create an OSSClient instance.
// When the OSSClient instance is no longer used, call the shutdown method to release resources.
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
conf.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(new DefaultCredentialProvider(credentialsProvider.getCredentials()))
.clientConfiguration(conf)
.region(region)
.cloudBoxId(cloudBoxId)
.build();
try {
// Create a PutObjectRequest object.
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
// To set the storage class and access permissions during the upload, see the following sample code.
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
// Upload the file.
ossClient.putObject(putObjectRequest);
} 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 alibabacloud_oss_v2 as oss
# Obtain access credentials from environment variables. Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables before you run the code.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# The region where the CloudBox is located. For example, cn-hangzhou.
cfg.region = "cn-hangzhou"
# The CloudBox data domain name, in the format CloudboxId.Region.oss-cloudbox.aliyuncs.com.
cfg.endpoint = "cb-xxxx.cn-hangzhou.oss-cloudbox.aliyuncs.com"
# The CloudBox ID.
cfg.cloud_box_id = "cb-xxxx"
client = oss.Client(cfg)
# Upload data to the specified object.
result = client.put_object(oss.PutObjectRequest(
bucket="examplebucket",
key="exampledir/exampleobject.txt",
body=b"Hello OSS",
))
print(f"status code: {result.status_code}, etag: {result.etag}")package main
import (
"context"
"log"
"strings"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// The region where the CloudBox is located. For example, cn-hangzhou.
region := "cn-hangzhou"
// Obtain access credentials from environment variables. Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables before you run the code.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region).
// The CloudBox data domain name, in the format CloudboxId.Region.oss-cloudbox.aliyuncs.com.
WithEndpoint("cb-xxxx.cn-hangzhou.oss-cloudbox.aliyuncs.com").
// The CloudBox ID.
WithCloudBoxId("cb-xxxx")
client := oss.NewClient(cfg)
// Upload data to the specified object.
result, err := client.PutObject(context.TODO(), &oss.PutObjectRequest{
Bucket: oss.Ptr("examplebucket"),
Key: oss.Ptr("exampledir/exampleobject.txt"),
Body: strings.NewReader("Hello OSS"),
})
if err != nil {
log.Fatalf("failed to put object %v", err)
}
log.Printf("put object result:%#v\n", result)
}ossutil kullanın
ossutil kullanarak basit yükleme işlemleri gerçekleştirmek için cp (dosya yükleme) komutuna bakın.
REST API kullanın
Uygulamanız geniş kapsamlı özelleştirme gerektiriyorsa REST API'yi doğrudan çağırabilirsiniz. Bu işlem, imzayı manuel olarak hesaplamak için kod yazmanızı gerektirir. Daha fazla bilgi için PutObject API referansına bakın.
3. Adım: Nesne indirin
Alibaba Cloud SDK kullanın
Java, Python veya Go için OSS SDK'yı kullanarak (Java SDK 3.15.0 veya sonrası, Python SDK V2 1.1.1 veya sonrası, Go SDK V2 v1.2.1 veya sonrası) nesneleri indirebilirsiniz. CloudBox üzerindeki OSS için Python ve Go SDK'ları, genel cloud OSS ile aynı şekilde çağrılır. İstemci oluşturma hakkında bilgi için SDK desteği konusuna bakın. Aşağıdaki kod örnekleri Java, Python ve Go SDK'larını kullanmaktadır.
package com.aliyun.oss.demo;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
public class Demo {
public static void main(String[] args) throws Exception {
// Specify the data endpoint of the OSS on CloudBox bucket.
String endpoint = "https://cb-f8z7yvzgwfkl9q0h****.cn-hangzhou.oss-cloudbox.aliyuncs.com";
// 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 configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the OSS on CloudBox bucket. For example, examplebucket.
String bucketName = "examplebucket";
// Specify the region where the OSS on CloudBox bucket is located.
String region = "cn-hangzhou";
// Specify the ID of the CloudBox.
String cloudBoxId = "cb-f8z7yvzgwfkl9q0h****";
// Specify the full path of the object, excluding the bucket name. For example, exampledir/exampleobject.txt.
String objectName = "exampledir/exampleobject.txt";
// Specify the local file path to save the downloaded object.
String pathName = "D:\\localpath\\examplefile.txt";
// Create an OSSClient instance using Signature Version 4 (V4).
// Call shutdown() to release resources when the client is no longer needed.
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
conf.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(new DefaultCredentialProvider(credentialsProvider.getCredentials()))
.clientConfiguration(conf)
.region(region)
.cloudBoxId(cloudBoxId)
.build();
try {
// Download the object to the specified local file.
// If the file exists, it is overwritten. If it does not exist, a new file is created.
// If you do not specify a local path, the file is saved to the path of the project to which the sample program belongs.
ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
} catch (OSSException oe) {
System.out.println("OSS rejected the request.");
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("Client failed to communicate with OSS.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}import alibabacloud_oss_v2 as oss
# Obtain access credentials from environment variables. Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables before you run the code.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# The region where the CloudBox is located. For example, cn-hangzhou.
cfg.region = "cn-hangzhou"
# The CloudBox data domain name, in the format CloudboxId.Region.oss-cloudbox.aliyuncs.com.
cfg.endpoint = "cb-xxxx.cn-hangzhou.oss-cloudbox.aliyuncs.com"
# The CloudBox ID.
cfg.cloud_box_id = "cb-xxxx"
client = oss.Client(cfg)
# Download the object to a local file.
result = client.get_object_to_file(oss.GetObjectRequest(
bucket="examplebucket",
key="exampledir/exampleobject.txt",
), "download.txt")
print(f"status code: {result.status_code}, content length: {result.content_length}")package main
import (
"context"
"io"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
// The region where the CloudBox is located. For example, cn-hangzhou.
region := "cn-hangzhou"
// Obtain access credentials from environment variables. Set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables before you run the code.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region).
// The CloudBox data domain name, in the format CloudboxId.Region.oss-cloudbox.aliyuncs.com.
WithEndpoint("cb-xxxx.cn-hangzhou.oss-cloudbox.aliyuncs.com").
// The CloudBox ID.
WithCloudBoxId("cb-xxxx")
client := oss.NewClient(cfg)
// Download the specified object.
result, err := client.GetObject(context.TODO(), &oss.GetObjectRequest{
Bucket: oss.Ptr("examplebucket"),
Key: oss.Ptr("exampledir/exampleobject.txt"),
})
if err != nil {
log.Fatalf("failed to get object %v", err)
}
defer result.Body.Close()
data, _ := io.ReadAll(result.Body)
log.Printf("get object content length:%d\n", len(data))
}ossutil kullanın
ossutil kullanarak basit indirme işlemleri gerçekleştirmek için cp (dosya indirme) komutuna bakın.
REST API kullanın
Uygulamanız geniş kapsamlı özelleştirme gerektiriyorsa REST API'yi doğrudan çağırabilirsiniz. Bu işlem, imzayı manuel olarak hesaplamak için kod yazmanızı gerektirir. Daha fazla bilgi için GetObject API referansına bakın.