Build a Spring Cloud application that uploads, downloads, and reads files from Object Storage Service (OSS), then deploy it to Enterprise Distributed Application Service (EDAS) without modifying code or configuration.
Why use OSS
OSS is developed by Alibaba Cloud to provide secure, cost-effective, and highly reliable storage services. It allows you to store large amounts of data in the cloud. OSS provides platform-independent RESTful API operations, which means you can store and access all types of data in applications developed with Spring Cloud.
Prerequisites
Before you begin, make sure that you have:
An Alibaba Cloud account with OSS activated
An OSS bucket
An AccessKey pair (AccessKey ID and AccessKey secret) from the Security Management page
The OSS endpoint for your bucket's region (see Regions and endpoints)
JDK 8 or later and Maven installed locally
How it works
Spring Cloud AliCloud OSS integrates Spring Cloud applications with Alibaba Cloud OSS. After you add the starter dependency and configure your credentials, you can:
Inject an
OSSclient directly into your Spring beansAccess OSS objects as Spring
Resourceinstances by using@Value("oss://...")Deploy the same application to EDAS without modifying code or configuration
Set up the Maven project
Create a Maven project named
oss-example.Add the following dependencies to
pom.xml:Spring Boot 1.x has reached end of life. If you must use Spring Boot 1.x, use version 1.5.x with Spring Cloud Edgware and Spring Cloud Alibaba 1.5.1.RELEASE.
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> <relativePath/> </parent> <dependencies> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alicloud-oss</artifactId> <version>2.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.SR1</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>Create a package named
spring.cloud.alicloud.ossundersrc/main/java.
Create the application entry point
Create the startup class OssApplication in the spring.cloud.alicloud.oss package. On startup, it checks whether the target bucket exists and creates it if needed.
package spring.cloud.alicloud.oss;
import com.aliyun.oss.OSS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.net.URISyntaxException;
@SpringBootApplication
public class OssApplication {
// Replace with your actual bucket name
public static final String BUCKET_NAME = "test-bucket";
public static void main(String[] args) throws URISyntaxException {
SpringApplication.run(OssApplication.class, args);
}
@Bean
public AppRunner appRunner() {
return new AppRunner();
}
class AppRunner implements ApplicationRunner {
@Autowired
private OSS ossClient;
@Override
public void run(ApplicationArguments args) throws Exception {
try {
if (!ossClient.doesBucketExist(BUCKET_NAME)) {
ossClient.createBucket(BUCKET_NAME);
}
} catch (Exception e) {
System.err.println("oss handle bucket error: " + e.getMessage());
System.exit(-1);
}
}
}
}Add a sample file
Create a file named oss-test.json in src/main/resources:
{
"name": "oss-test"
}Create the REST controller
Create OssController in the spring.cloud.alicloud.oss package. This controller exposes three endpoints for uploading, downloading, and reading files through the Spring Resource interface.
package spring.cloud.alicloud.oss;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.OSSObject;
import org.apache.commons.codec.CharEncoding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.nio.charset.Charset;
@RestController
public class OssController {
@Autowired
private OSS ossClient;
// Access an OSS object as a Spring Resource
@Value("oss://" + OssApplication.BUCKET_NAME + "/oss-test.json")
private Resource file;
/**
* Uploads oss-test.json from the classpath to the OSS bucket.
*/
@GetMapping("/upload")
public String upload() {
try {
ossClient.putObject(OssApplication.BUCKET_NAME, "oss-test.json", this
.getClass().getClassLoader().getResourceAsStream("oss-test.json"));
} catch (Exception e) {
e.printStackTrace();
return "upload fail: " + e.getMessage();
}
return "upload success";
}
/**
* Reads the OSS object through the Spring Resource interface.
*/
@GetMapping("/file-resource")
public String fileResource() {
try {
return "get file resource success. content: " + StreamUtils.copyToString(
file.getInputStream(), Charset.forName(CharEncoding.UTF_8));
} catch (Exception e) {
e.printStackTrace();
return "get resource fail: " + e.getMessage();
}
}
/**
* Downloads the OSS object directly through the OSS client.
*/
@GetMapping("/download")
public String download() {
try {
OSSObject ossObject = ossClient.getObject(OssApplication.BUCKET_NAME, "oss-test.json");
return "download success, content: " + IOUtils
.readStreamAsString(ossObject.getObjectContent(), CharEncoding.UTF_8);
} catch (Exception e) {
e.printStackTrace();
return "download fail: " + e.getMessage();
}
}
}Endpoint summary:
| Endpoint | Method | Description |
|---|---|---|
/upload | GET | Uploads oss-test.json from the classpath to your OSS bucket |
/file-resource | GET | Reads the file from OSS through Spring's Resource abstraction (@Value("oss://...")) |
/download | GET | Retrieves the file directly through the OSS client |
Configure credentials and endpoint
Get your AccessKey ID and AccessKey secret from the Security Management page.
Get the endpoint for your bucket's region. See Regions and endpoints.
Create
application.propertiesinsrc/main/resources: Replace the following placeholders with your actual values:Placeholder Description Example <your-access-key>AccessKey ID LTAI5tXxx<your-secret-key>AccessKey secret xXxXxXx<your-endpoint>Regional endpoint prefix oss-cn-hangzhouspring.application.name=oss-example server.port=18084 # Replace with your actual credentials and endpoint spring.cloud.alicloud.access-key=<your-access-key> spring.cloud.alicloud.secret-key=<your-secret-key> spring.cloud.alicloud.oss.endpoint=<your-endpoint>.aliyuncs.com management.endpoints.web.exposure.include=*
Verify the result
Run the
mainmethod ofOssApplicationto start the service.Open
http://127.0.0.1:18084/uploadin your browser. Ifupload successappears, the file was uploaded.Verify in the OSS console: navigate to your bucket, click Files in the left-side navigation pane, and confirm that
oss-test.jsonappears in the file list.Open
http://127.0.0.1:18084/downloadto download the file. The expected output is:{ "name": "oss-test" }Open
http://127.0.0.1:18084/file-resourceto read the file through the Spring Resource interface. The expected output is:{ "name": "oss-test" }
If any step fails, check the console logs for errors, fix the issue, and restart the application.
Deploy to EDAS
Spring Cloud AliCloud OSS is developed to respond to the needs of migrating applications from their original development environments to EDAS. Deploy your application without modifying code or configuration.
For deployment steps, see:
Configuration reference
| Property | Description | Example |
|---|---|---|
spring.cloud.alicloud.access-key | AccessKey ID for authentication | LTAI5tXxx |
spring.cloud.alicloud.secret-key | AccessKey secret for authentication | xXxXxXx |
spring.cloud.alicloud.oss.endpoint | OSS regional endpoint | oss-cn-hangzhou.aliyuncs.com |
server.port | Application port | 18084 |
spring.application.name | Spring application name | oss-example |