一、文件存儲架構演進
1.1 單機-普通上傳
1.2 分布式-普通上傳
由於負載均衡的存在,可能導致儲存的時候路由到A服務器,獲取的時候路由到B服務器,導致文件獲取不到。
1.3 分布式-雲存儲
為文件存儲單獨設置一個服務器,哪怕有商品服務存在負載均衡,但是都存儲在另外的文件存儲服務器。
二、雲存儲方案:阿里雲OSS(object storage service)
2.1 相關術語
其中“訪問密鑰”很關鍵,說白了就是上傳文件到OSS時所需的賬號和密碼
三、文件上傳架構演進
3.1 普通上傳方式
優點:安全。通過自己的應用服務器上傳,賬號密碼不會泄露。
缺點:每個請求要過一遍自己的應用服務器,高峰期會導致服務器資源緊張,出現性能瓶頸....
3.2 服務端簽名后直傳 (推薦)
四、實踐:普通上傳方式
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:
-
On the Alibaba Cloud console, click your avatar on the upper-right corner and click accesskeys. Or visit User Management page directly:
-
Get your accessKey、secretKey:
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); } }
五、實踐:服務端簽名后直傳