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);
     }
    
 }

 

 

五、實踐:服務端簽名后直傳

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM