SpringCloud Alibaba- 分布式文件存储 OSS

一、文件存储架构演进

1.1 单机-普通上传

1.2 分布式-普通上传

由于负载均衡的存在,可能导致储存的时候路由到A服务器,获取的时候路由到B服务器,导致文件获取不到。

1.3 分布式-云存储

为文件存储单独设置一个服务器,哪怕有商品服务存在负载均衡,但是都存储在另外的文件存储服务器。

二、云存储方案:阿里云OSS(object storage service)

2.1 相关术语

其中“访问密钥”很关键,说白了就是上传文件到OSS时所需的账号和密码

三、文件上传架构演进

3.1 普通上传方式

优点:安全。通过自己的应用服务器上传,账号密码不会泄露。

缺点:每个请求要过一遍自己的应用服务器,高峰期会导致服务器资源紧张,出现性能瓶颈....

3.2 服务端签名后直传 (推荐)

 

四、实践:普通上传方式

参考官方文档:https://github.com/alibaba/aliyun-spring-boot/tree/master/aliyun-spring-boot-samples/aliyun-oss-spring-boot-sample

4.1 引入依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>aliyun-oss-spring-boot-starter</artifactId>
</dependency>

4.2 配置accessKeyId, secretAccessKey, endPoint

To get accessKey, secretKey, follow these steps:

  1. On the Alibaba Cloud console, click your avatar on the upper-right corner and click accesskeys. Or visit User Management page directly:

    undefined

  2. Get your accessKey、secretKey:

    undefined

Note: If you are using STS, you should configure securityToken in addition to accessKey, secretKey, and endpoint.

4.3 直接使用注入的OSSClient

Inject OSSClient and use it to upload files to the OSS server and download a file from OSS server.

Note: Direct injection into the OSSClient mode is typically used for scenarios where you need to handle a large number of file objects. If you only need to read the contents of the file object, OSS Starter also supports reading the file in Resource mode.

 @Service
 public class YourService {
     @Autowired
     private OSSClient ossClient;

    //下载文件到本地
     public void saveFile() {
         ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File("pathOfYourLocalFile"));
     }

     //上传文件到阿里云oss
     public void uploadFile(){
         InputStream inputStream = new FileInputStream("c:\pic\test.jpg");
         ossClient.putObject("bucketName","fileName",inputStream);
     }
    
 }

五、实践:服务端签名后直传

原文地址:https://www.cnblogs.com/frankcui/p/15204219.html