Spring Boot with Alibaba Cloud Object Storage Service

Alibaba Cloud
5 min readJun 18, 2019

By Dassi Orleando, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud’s incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.

Overview

Alibaba Cloud Object Storage Service (OSS) is an encrypted storage service that allows you to safely save, back up, and archive any volume of data in the cloud. OSS is cost-effective, highly secure while being a very reliable solution for any use. It’s possible to interact with it using a restful API.

In this article, we’ll show how to do some basic OSS operations into a spring-boot application using an SDK interface provided by Alibaba Cloud wrapped on top of a spring dependency.

Prerequisites

  1. Basic knowledge of Spring Boot
  2. An Alibaba Cloud account

Concepts

Let’s grab some important concepts around the OSS service:

  • Storage Class: OSS provides three storage classes: Standard, Infrequent Access, and Archive. These storage classes cover various data storage scenarios from hot data to cold data. For more information, see Introduction to storage classes.
  • Bucket: A bucket is a container for objects stored in OSS. Every object is contained in a bucket.
  • Objects: which are files, are the fundamental entities stored in OSS. An object is defined by some metadata, data and key. The key is a unique object field present in a bucket.
  • Region: represents the physical location of an OSS data center. You can choose the region that has the least latency while being affordable for you.
  • Endpoint: it’s nothing more than the domain name used to access the OSS. OSS provides external services through HTTP RESTful APIs. Different regions use different endpoints. Let’s note that each region has its endpoint.
  • AccessKey: An AccessKey (AK) is composed of an AccessKeyId and an AccessKeySecret.

More details of OSS can be found here.

Dependencies

The following Maven dependency is used to make the whole logic possible, it’s the spring wrapper for the SDK interface:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
<version>0.2.1.RELEASE</version>
</dependency>

The most recent version at the time of writing this article is the 0.2.1.RELEASE accessible on Maven Central Repository.

Connect to OSS

To perform any operation on our OSS we first need to connect ourselves giving us the required permissions to perform authenticated actions from our application.

It’s important to create an Alibaba Cloud account to proceed with the other steps. If you don’t have one already, go ahead and create your account through this link.

Let’s assume that we have a fully working account. Now let’s head on to the most important step, which is getting our unique credentials.

On the top bar of our dashboard, there is our profile pic on the very right side just hover it we have listed more menu items where we’ll be selecting AccessKey as illustrated in the following image:

We’ll then be redirected to another interface allowing us to manage our access keys:

  • Create
  • Disable
  • Delete access key

Once created an access key we’ll have such a screen where we’ll need to click on the Show action to view the Access Key Secret:

Now heading again in the source code part of this article, let’s suppose we have both the Access Key ID & Secret, the next step is to include these details into the application.properties file of our Spring application.

Here’s the full content of our application.properties:

spring.application.name=spring-alibaba-ossserver.port=8080spring.cloud.alicloud.access-key=******fill***yours****here****
spring.cloud.alicloud.secret-key=******fill***yours****here****
spring.cloud.alicloud.oss.endpoint=oss-cn-hangzhou-internal.aliyuncs.com
management.endpoints.web.exposure.include=*

Note: here we’ve all the Access Key details, the port (8080) to use to launch the App and the OSS endpoint(where our buckets and objects will be stored).

The endpoint depends of the region chosen (in our case it’s oss-cn-hangzhou), here’s the regions full list to identify the correct value to use.

Use OSSClient to Save/Query Data

Now that the whole thing is well setting up, we can perform some operations directly under our account to use Alibaba Cloud OSS service.

We need to make sure OSS service is activated into our account by clicking on the call to action in the dashboard as illustrated in this screenshot:

Shown below the overview of the OSS, here we can also perform the same operations graphically plus accessing statistics of use in entrance:

The recommended graphical management tool developed by Alibaba Cloud is ossbrowser.

If interested in any graphical (web interface) practical cases here are some links:

It’s important to understand the concept of bucket we’ve highlighted very up in the Concepts section, listed below some operations after having injected ossClient into our controller/service.

Let’s inject the ossClient first in one line:

@Autowired
private OSS ossClient;

Create Bucket

ossClient.createBucket("Bucket name goes here");

Check Bucket

Here’s the action to check if a bucket exists:

ossClient.doesBucketExist("Bucket name goes here");

Put Object

ossClient.putObject("oss-test", "spring-alibaba-oss.json", this
.getClass().getClassLoader().getResourceAsStream("spring-alibaba-oss.json"));

We should understand that here oss-test is our bucket name (supposing created), spring-alibaba-oss.json is the unique object’s key and the third parameter is the InputStream (here it’s just a Json file into our resources folder).

Get Object

OSSObject ossObject = ossClient.getObject("oss-test", "spring-alibaba-oss.json");

Here we see how it’s straightforward to query an object by using its key (spring-alibaba-oss.json).

Delete Object

ossClient.deleteObject("oss-test", "spring-alibaba-oss.json");

To delete an object by its key again.

Check Object

ossClient.doesObjectExist("oss-test", "spring-alibaba-oss.json")

Resources

Here is how we make it work with the restful controller:

Check existence

@GetMapping("/buckets/exist/{bucketName}")
public boolean bucketExists(@PathVariable String bucketName) {
return ossClient.doesBucketExist(bucketName);
}
@GetMapping("/objects/exist/{objectName}")
public boolean objectExists(@PathVariable String objectName) {
return ossClient.doesObjectExist(SpringAlibabaOssApplication.BUCKET_NAME, objectName);
}

Upload / download

@GetMapping("/upload")
public String upload() {
try {
ossClient.putObject("oss-test", "spring-alibaba-oss.json", this
.getClass().getClassLoader().getResourceAsStream("spring-alibaba-oss.json"));
} catch (Exception e) {
e.printStackTrace();
return "upload fail: " + e.getMessage();
}
return "upload success";
}
@GetMapping("/download")
public String download() {
try {
OSSObject ossObject = ossClient.getObject(SpringAlibabaOssApplication.BUCKET_NAME, "spring-alibaba-oss.json");
return "download success, content: " + IOUtils
.readStreamAsString(ossObject.getObjectContent(), CharEncoding.UTF_8);
} catch (Exception e) {
e.printStackTrace();
return "download fail: " + e.getMessage();
}
}

Up here we’ve the two rest calls to upload and download our file located into the resources folder.

Conclusion

In this article, we’ve seen how to use the Alibaba Cloud OSS service within a Spring-Boot project plus doing some operations on our buckets/objects.

The full source code can be found here.

Reference

https://www.alibabacloud.com/blog/spring-boot-with-alibaba-cloud-object-storage-service_594905?spm=a2c41.13033977.0.0

--

--

Alibaba Cloud

Follow me to keep abreast with the latest technology news, industry insights, and developer trends. Alibaba Cloud website:https://www.alibabacloud.com