This topic describes an example of how to implement Object Storage Service (OSS) in a local Spring Cloud application and host the application to Enterprise Distributed Application Service (EDAS).

Why is OSS used?

OSS is a secure, reliable, low-cost, and high-capacity storage service from Alibaba Cloud. OSS provides platform-independent RESTful APIs, allowing you to store and access any types of data in applications developed by Spring Cloud.

Preparations

Before implementing OSS in an application, use your Alibaba Cloud account to create a bucket in OSS.

  1. t4331.dita#task_njz_hf4_tdb.
  2. t4333.dita#task_u3p_3n4_tdb.

Implement OSS locally

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

    The following takes Spring Boot 2.1.4.RELEASE and Spring Cloud Greenwich.SR1 as an 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, Spring Cloud Edgware, and Spring Cloud Alibaba 1.5.1.RELEASE.
    • Spring Boot 1.x has expired, so we recommend that you use a later version of Spring Boot to develop applications.
  3. Create a package, such as spring.cloud.alicloud.oss, in src/main/java.
  4. Create the startup class 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. Add the sample file oss-test.json to be uploaded in the src/main/resources path.
     {
       "name": "oss-test"
     }                        
  6. In the spring.cloud.alicloud.oss package, create the class OssController and add configuration to implement functions such as upload, download, and file retrieval through the Resource specifications of Spring.
        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 add the configuration locally.
    1. Go to the Security Management page and retrieve the AccessKey ID and AccessKey secret.
    2. Retrieve the endpoint based on the region where the created bucket is located. For more information, see t4350.dita#concept_zt4_cvy_5db.
    3. Create the file application.properties in the src/main/resources path and add the configuration of the AccessKey ID, AccessKey secret, and endpoint.
      spring.application.name=oss-example
      server.port=18084
      # Enter the AccessKey ID.
      spring.cloud.alicloud.access-key=xxxxx
      # Enter the AccessKey secret.
      spring.cloud.alicloud.secret-key=xxxxx
      # Enter the endpoint.
      spring.cloud.alicloud.oss.endpoint=xxx.aliyuncs.com
      management.endpoints.web.exposure.include=*                                
  8. Run the main function in OssApplication to start the service.

Verify the result

  1. Visit http://127.0.0.1:18084/upload in your web browser.
    The sample file oss-test.json has been uploaded if upload success is displayed. Otherwise, check the local code to solve the problem. Then, run the main function in OssApplication again and start the service.
  2. Log on to the OSS console, go to the bucket that stores the uploaded file, and click Files on the top.
    The file has been uploaded if oss-test.json is displayed. Otherwise, check the local code to solve the problem. Then, run the main function in OssApplication again and start the service.
  3. Visit http://127.0.0.1:18084/upload 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 retrieve the sample file oss-test.json.
     {
       "name": "oss-test"
     }                        

Deploy applications to EDAS

Spring Cloud Alibaba Cloud OSS is designed for migrating applications from the development environment to EDAS. You can directly deploy applications to EDAS without modifying any code or configurations. For more information about deployment methods and procedures, see t1838945.dita#concept_2038298.