This topic provides an example to describe how to implement Object Storage Service (OSS) features in an on-premises Spring Cloud application and use Enterprise Distributed Application Service (EDAS) to host the application.

Why is OSS used?

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 APIs and allows you to store and access all the types of data in applications that are developed by Spring Cloud.

Prerequisites

Before you implement OSS features in an application, a bucket is created in OSS by using your Alibaba Cloud account.

  1. Activate OSS
  2. Create buckets

Implement OSS features in an on-premises environment

  1. Create a Maven project named oss-example.
  2. Add the following dependencies to the pom.xml file:

    Spring Boot 2.1.4.RELEASE and Spring Cloud Greenwich.SR1 are used in the example.

     <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>                        
    Note
    • If you want to use Spring Boot 1.x, use Spring Boot 1.5.x and Spring Cloud Edgware. The corresponding version of Spring Cloud Alibaba is 1.5.1.RELEASE.
    • Spring Boot 1.x has reached end of life. Therefore, we recommend that you use a later version of Spring Boot to develop your applications.
  3. Create a package, such as spring.cloud.alicloud.oss, in src/main/java.
  4. Create a startup class named OssApplication for oss-example in the spring.cloud.alicloud.oss package.
        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 {
            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);
                    }
                }
            }
        }                        
  5. In the src/main/resources path, add a sample file to be uploaded. The sample file is named oss-test.json in the example.
     {
       "name": "oss-test"
     }                        
  6. Create a class named OssController in the spring.cloud.alicloud.oss package and add configurations to implement features, such as obtaining files through the Resource interface of Spring, uploading data, and downloading data.
        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;
            @Value("oss://" + OssApplication.BUCKET_NAME + "/oss-test.json")
            private Resource file;
            @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";
            }
            @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();
                }
            }
            @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();
                }
            }
        }                        
  7. Obtain the AccessKey ID, AccessKey secret, and endpoint, and then add the configurations in your on-premises environment.
    1. Go to the Security Management page and obtain the AccessKey ID and the AccessKey secret.
    2. Obtain the endpoint based on the region where the bucket is deployed. For more information, see Regions and endpoints.
    3. Create a file named application.properties in the src/main/resources path and add the configurations of the AccessKey ID, AccessKey secret, and endpoint.
      spring.application.name=oss-example
      server.port=18084
      # Specify the AccessKey ID.
      spring.cloud.alicloud.access-key=xxxxx
      # Specify the AccessKey secret.
      spring.cloud.alicloud.secret-key=xxxxx
      # Specify the endpoint.
      spring.cloud.alicloud.oss.endpoint=xxx.aliyuncs.com
      management.endpoints.web.exposure.include=*                                
  8. Run the main function of OssApplication to start the service.

Verify the result

  1. Visit http://127.0.0.1:18084/upload in your web browser.
    If upload success appears, the sample file oss-test.json has been uploaded. Otherwise, check the code in the on-premises environment for troubleshooting. Then, run the main function of OssApplication again to start the service.
  2. Log on to the OSS console and go to the bucket that stores the uploaded file. Then, in the left-side navigation pane, click Files and check whether the sample file has been uploaded.
    If oss-test.json appears, the file has been uploaded. Otherwise, check the code in the on-premises environment for troubleshooting. Then, run the main function of OssApplication again to start the service.
  3. Visit http://127.0.0.1:18084/download in your web browser to download the oss-test.json file.
     {
       "name": "oss-test"
     }                        
  4. Visit http://127.0.0.1:18084/file-resource in your web browser to obtain the sample file oss-test.json.
     {
       "name": "oss-test"
     }                        

Deploy the application to EDAS

Spring Cloud AliCloud OSS is developed to respond to the needs of migrating applications from their original development environments to EDAS. You can deploy applications to EDAS without the need to modify the code or configurations. For more information about deployment methods and steps, see Create and deploy applications (Kubernetes) and Overview.