Overview and usage steps of alicloud storage OSS (JAVA)

Posted by biscutty on Sat, 22 Jan 2022 03:47:15 +0100

1. What is object storage OSS

Alibaba cloud object storage OSS (Object Storage Service) is a massive, secure, low-cost, and highly persistent cloud storage service provided by Alibaba cloud. The data design persistence shall not be less than 99.99999999% (12 9S), and the service availability (or business continuity) shall not be less than 99.995%.

OSS has a platform independent RESTful API interface. You can store and access any type of data in any application, anytime and anywhere.

You can easily move massive data into or out of Alibaba cloud OSS using the API, SDK interface or OSS migration tool provided by Alibaba cloud. After the data is stored in alicloud OSS, you can choose Standard storage as the main storage method for mobile applications, large websites, image sharing or hot audio and video, or you can choose low-frequency access storage with lower cost and longer storage period, Archive storage Cold Archive is used as a storage method for infrequently accessing data.

2. OSS related concepts

  • Storage Class
    OSS provides four storage types: standard, low-frequency access, archiving and cold archiving, covering all kinds of data storage scenarios from hot to cold. The standard storage type provides object storage services with high persistence, high availability and high performance, and can support frequent data access; The low-frequency access storage type is suitable for storing infrequently accessed data for a long time (the average access frequency is 1 to 2 times per month), and the storage unit price is lower than the standard type; The archive storage type is suitable for archive data that needs to be stored for a long time (more than half a year is recommended); Cold archive storage is suitable for extremely cold data that needs to be stored for a long time.

  • Storage space (Bucket)
    Storage space is the container you use to store objects. All objects must belong to a storage space. Storage space has various configuration attributes, including region, access rights, storage type, etc. You can create different types of storage space to store different data according to your actual needs.

  • Object
    Objects are the basic units of OSS for storing Data, also known as OSS files. An object consists of Object Meta, user Data, and file name (Key). The object is identified by a unique Key inside the storage space. Object Meta information is a set of Key value pairs, which represents some attributes of the object, such as the last modification time, size and other information. At the same time, you can also store some customized information in the meta information.

  • Region
    Region indicates the physical location of the OSS data center. You can select an appropriate region to create a Bucket according to expenses, request sources, etc. For more information, see OSS enabled regions.

  • Access domain name (Endpoint)
    Endpoint indicates the domain name of OSS external services. OSS provides external services in the form of HTTP RESTful API. When accessing different regions, different domain names are required. The domain names needed to access the same region through intranet and extranet are also different.

  • Access key
    AccessKey is abbreviated as AK, which refers to the accessKey ID and AccessKey Secret used in access authentication. OSS verifies the identity of the sender of a request by using accessKey ID and AccessKey Secret symmetric encryption. AccessKey ID is used to identify the user; AccessKey Secret is the key used by the user to encrypt the signature string and OSS to verify the signature string. It must be kept confidential.

3. OSS common operations

  • -Create Bucket
    Before uploading objects to OSS, you need to create a bucket for storing files. Bucket has various configuration attributes, including region, access rights and other metadata.

  • Upload file
    After the Bucket is created, you can upload files of different sizes in a variety of ways.

  • Download File
    After the file is uploaded, you can download the file to the default path of the browser or the locally specified path.

  • Enumeration file
    When a large number of files are stored in the Bucket, you can choose to list all or part of the files in the Bucket.

  • Delete file
    When you no longer need to keep uploaded files, you can manually delete single or multiple files, or you can automatically delete single or multiple files by configuring lifecycle rules.

4. JAVA backend integration alicloud OSS

prerequisite

Use java version 1.7 and above***
You can view the Java version through the command java -version**

  • Create a maven project OSS with IDEA

  • Introduce alicloud oss dependencies into the pom file

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.10.2</version>
</dependency>
  • Write configuration file application properties

server.port=8002

spring.application.name=service-oss

spring.profiles.active=dev
#Alibaba cloud oss
#Different servers have different addresses
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.oss.file.keyid=
aliyun.oss.file.keysecret=
aliyun.oss.file.bucketname=

endpoint is region

keyid is AccessKey ID

keysecret is AccessKey Secret

Bucket name is the name of the bucket created

  • Create target file

  • Specific code

The code of constantproperiesutile is as follows

mport org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

//After the project is started and the spring interface is loaded, the method of the interface is executed
@Component
public class ConstantPropertiesUtils implements InitializingBean {
    //Read configuration file
    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.keyid}")
    private String keyid;

    @Value("${aliyun.oss.file.keysecret}")
    private String keysecret;

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketname;


    public static String END_POINT;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;

    //Define public static constants
    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT = endpoint;
        ACCESS_KEY_ID = keyid;
        ACCESS_KEY_SECRET = keysecret;
        BUCKET_NAME = bucketname;
    }
}

The startup class OssApplication code is as follows

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;


@ComponentScan(basePackages = {"Fill in the path of the package, such as com.hou."})
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class OssApplication {

    public static void main(String[] args) {
        SpringApplication.run(OssApplication.class, args);
    }
}

Control layer code

import com.atguigu.commonutils.R;
import com.atguigu.oss.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/eduoss/fileoss")
@CrossOrigin
public class OssController {
    @Autowired
    private OssService ossService;

    //Method of uploading Avatar
    @PostMapping
    public R uploadOssFile(MultipartFile file) {
        //Get uploaded file, MultipartFile
        //Return the url to upload oss
        String url = ossService.uploadFileAvatar(file);
        return R.ok().data("url", url);
    }
}

Service layer code

import org.springframework.web.multipart.MultipartFile;

public interface OssService {

    /**
     * Upload files to alicloud
     *
     * @param file
     * @return
     */
    String uploadFileAvatar(MultipartFile file);
}

Finally, the implementation method OssServiceImpl code

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {

        String endPoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        try {
// Create an OSSClient instance.
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

// Upload file stream.
            InputStream inputStream = file.getInputStream();

            //Get file name
            String fileOriginalFilename = file.getOriginalFilename();

            //Use uuid to add a unique value to the file name
            String uuid = UUID.randomUUID().toString().replace("-", "");
            fileOriginalFilename = uuid + fileOriginalFilename;

            String datePach = new DateTime().toString("yyyy/MM/dd");

            fileOriginalFilename = datePach + "/" + fileOriginalFilename;

            //Call oss to upload
            //The first parameter is BucketName, the second parameter is the path and name to upload to the oss file, and the third parameter is the input stream
            ossClient.putObject(bucketName, fileOriginalFilename, inputStream);

// Close the OSSClient.
            ossClient.shutdown();

            String url = "http://" + bucketName + "." + endPoint + "/" + fileOriginalFilename;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

5. Test

Testing with swagger
Browser input after server startup http://localhost:8002/swagger-ui.html start swagger


Finally, the test is successful. Find your own file on alicloud server

Some of the above contents are from Alibaba cloud official documents oss document

Topics: Java