OSS storage service quick start + distributed OSS storage

Table of contents

Introduction

1. What is OSS?

2、aliyun's access key

 3. OSS storage service

quick start

1. Introduce dependencies

2. Monolithic architecture

3. Distributed architecture

3.1. Configure the yml file in the common module

3.2. The common module creates the corresponding entity class and introduces the data in yml

3.3. Common module creates OSSUtil tool class

3.4. Introduce application-comm.yml into the web module

3.5. Testing


Introduction

1. What is OSS?

Alibaba Cloud console homepage (aliyun.com)  or Baidu all aliyun

The full English name of "OSS" is Object Storage Service, which translates into Chinese as "Object Storage Service". The official explanation is that object storage is a tool that uses HTTP API to store and retrieve unstructured data and metadata objects.

The vernacular explanation is to upload the files used by the system to the cloud hard disk. The cloud hard disk provides a series of services such as file download and upload. Such services and technologies can be collectively referred to as OSS. There are many manufacturers in the industry that provide OSS services. They are well-known, commonly used and mature. Blue Team Cloud at scale and more.

Not only aliyun's OSS storage service, but also Tencent Cloud's OBS, Tencent Cloud's COS, etc., can all be implemented through the SDK interface.

2、aliyun's access key

 After creating your own accessKey, be sure to remember your Key and Secret.

 3. OSS storage service

 

 Create your own bucket (Bucket). After the creation is completed, click on your own bucket name.

Click on the overview, and there will be an endipint domain point  at the end.

quick start

I will explain OSS storage in two modules. The first is a single architecture that can be used directly for rapid development. The second is OSS storage with a distributed architecture commonly used by companies.

1. Introduce dependencies

<!--        OSS对象存储-->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.10.2</version>
        </dependency>
 <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>

2. Monolithic architecture

package com.dongyimai.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.UUID;

public class OSSUtil implements Serializable {


    public static String uploadFile(MultipartFile file) {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
//在上述csdn中的OSS存储服务介绍了如何获取下面的4个信息    
        String endpoint = "自己存储服务的域点";
        // 强烈建议不要把访问凭证保存到工程代码里,否则可能导致访问凭证泄露,威胁您账号下所有资源的安全。本代码示例以从环境变量中获取访问凭证为例。运行本代码示例之前,请先配置环境变量。
        
String accessKeyId = "自己的accessKey";
        String accessKeySecret = "自己的accessKeySecret";
        // 填写Bucket名称,例如examplebucket。
        String bucketName ="自己的桶";
        // 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        //防止重复覆盖设置随机数
       String uuid= UUID.randomUUID().toString().replaceAll("-","");
//        String objectName = imgPath;
        //文件名就变为: 随机数+a.jpg
        String fileName=uuid+file.getOriginalFilename();
        String dataPath = LocalDate.now().toString();
        String path = dataPath.replaceAll("-", "/");
        fileName=path+"/"+fileName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

        try {
        ossClient.putObject(bucketName, fileName,file.getInputStream());
        //返回的图片路径  https://+bucketName名称+.+endpoint+objectName+/+fileName
        String url="https://"+bucketName+"."+endpoint+"/"+fileName;
        return url;

    } catch ( OSSException oe) {
        System.out.println("Caught an OSSException, which means your request made it to OSS, "
                + "but was rejected with an error response for some reason.");
        System.out.println("Error Message:" + oe.getErrorMessage());
        System.out.println("Error Code:" + oe.getErrorCode());
        System.out.println("Request ID:" + oe.getRequestId());
        System.out.println("Host ID:" + oe.getHostId());
    } catch ( ClientException ce) {
        System.out.println("Caught an ClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with OSS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message:" + ce.getMessage());
    } catch (IOException e) {
            e.printStackTrace();
        } finally {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }
return null;
    }

}

When using a monolithic architecture, just use it as a util file.

The picture below shows the above code, just ignore it

 

3. Distributed architecture

My project structure: use the common module as a tool module, and the web startup class module introduces common dependencies

 

 

3.1. Configure the yml file in the common module

application-comm.yml

#当前的yaml的名称为:application-comm.yml
oss:
  endpoint: 自己的域点
  accessKeyId: 自己的accessKeyId
  accessKeySecret: 自己的accesskeySecret
  bucketName: 自己的桶

3.2. The common module creates the corresponding entity class and introduces the data in yml

package com.dongyimai.util;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component
@ConfigurationProperties(prefix = "oss")
public class ConstantPropertiesUtils  implements Serializable , InitializingBean {
 
    //读取配置文件的内容

    private String endpoint;

    private String accessKeyId;

    private String accessKeySecret;

    private String bucketName;
 


    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }


    @Override
    public String toString() {
        return "ConstantPropertiesUtils{" +
                "endpoint='" + endpoint + '\'' +
                ", accessKeyId='" + accessKeyId + '\'' +
                ", accessKeySecret='" + accessKeySecret + '\'' +
                ", bucketName='" + bucketName + '\'' +
                '}';
    }
    //定义公共静态常量
    public static String END_POINT;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;
//在当前文件加载之后执行该方法
//这个方法的意义就是:将已经被加载好的属性设置到静态常亮中,方便调用
    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT = endpoint;
        ACCESS_KEY_ID = accessKeyId;
        ACCESS_KEY_SECRET = accessKeySecret;
        BUCKET_NAME = bucketName;
    }
}

Note: When using @ConfigurationProperties(prefix = "XXX"), it will not be loaded and executed until springboot or spring project is started!

3.3. Common module creates OSSUtil tool class

package com.dongyimai.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.UUID;

public class OSSUtil implements Serializable {


    public static String uploadFile(MultipartFile file) {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = ConstantPropertiesUtils.END_POINT;
        // 强烈建议不要把访问凭证保存到工程代码里,否则可能导致访问凭证泄露,威胁您账号下所有资源的安全。本代码示例以从环境变量中获取访问凭证为例。运行本代码示例之前,请先配置环境变量。
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        // 填写Bucket名称,例如examplebucket。
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        // 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        //防止重复覆盖设置随机数
       String uuid= UUID.randomUUID().toString().replaceAll("-","");
//        String objectName = imgPath;
        //文件名就变为: 随机数+a.jpg
        String fileName=uuid+file.getOriginalFilename();
        String dataPath = LocalDate.now().toString();
        String path = dataPath.replaceAll("-", "/");
        fileName=path+"/"+fileName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

        try {
        ossClient.putObject(bucketName, fileName,file.getInputStream());
        //返回的图片路径  https://+bucketName名称+.+endpoint+objectName+/+fileName
        String url="https://"+bucketName+"."+endpoint+"/"+fileName;
        return url;

    } catch ( OSSException oe) {
        System.out.println("Caught an OSSException, which means your request made it to OSS, "
                + "but was rejected with an error response for some reason.");
        System.out.println("Error Message:" + oe.getErrorMessage());
        System.out.println("Error Code:" + oe.getErrorCode());
        System.out.println("Request ID:" + oe.getRequestId());
        System.out.println("Host ID:" + oe.getHostId());
    } catch ( ClientException ce) {
        System.out.println("Caught an ClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with OSS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message:" + ce.getMessage());
    } catch (IOException e) {
            e.printStackTrace();
        } finally {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }
return null;
    }

}

3.4. Introduce application-comm.yml into the web module

Because when two modules are involved, when the main startup class module is loaded, its application.yml configuration file will overwrite the application.yml in the submodule common, so we rename the yml in the common module applicationiton-comm.yml Then let the main startup class yml in the application.yml module be imported: just introduce the name after -

spring:
  profiles:
    include: comm

3.5. Testing

   @PostMapping("/upload")
    public ResultSet<String> upload( MultipartFile file){
        System.out.println("file="+file);
      
        String s = OSSUtil.uploadFile(file);
        //会获取到一个存储到OSS中的路径连接,可以直接通过百度查看图片
        System.out.println(s);
    return ResultSet.successData(s);
    }

 

Guess you like

Origin blog.csdn.net/wang20000102/article/details/132465831