雲計算

「一站式」兼容所有云廠商文件存儲Spring Boot 實現

背景

在互聯網發展的今天,近乎所有的雲廠商都提供對象存儲服務。一種海量、安全、低成本、高可靠的雲存儲服務,適合存放任意類型的文件。容量和處理能力彈性擴展,多種存儲類型供選擇,全面優化存儲成本。

當我們在使用對應雲廠商產品的時候,只需要引入對應嘗試提供的 SDK ,根據其開發文檔實現即可。但是當我們接入的雲廠商較多(或者能夠保證接口水平遷移時),我們要根據目標廠商接口破壞性修改

如下提供了幾家廠商接口 SDK 上傳實例:

阿里雲

// Endpoint以杭州為例,其它Region請按實際情況填寫。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";

// 創建OSSClient實例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 創建PutObjectRequest對象。
String content = "Hello OSS";
PutObjectRequest putObjectRequest = new PutObjectRequest("<yourBucketName>", "<yourObjectName>", new ByteArrayInputStream(content.getBytes()));

// 上傳字符串。
ossClient.putObject(putObjectRequest);

// 關閉OSSClient。
ossClient.shutdown();

華為雲

String endPoint = "https://your-endpoint";
String ak = "*** Provide your Access Key ***";
String sk = "*** Provide your Secret Key ***";
// 創建ObsClient實例
ObsClient obsClient = new ObsClient(ak, sk, endPoint);

obsClient.putObject("bucketname", "objectname", new File("localfile")); // localfile為待上傳的本地文件路徑,需要指定到具體的文件名

七牛雲

Configuration cfg = new Configuration(Region.region0());
UploadManager uploadManager = new UploadManager(cfg);
String accessKey = "your access key";
String secretKey = "your secret key";
String localFilePath = "/home/qiniu/test.png";
String key = null;

Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
Response response = uploadManager.put(localFilePath, key, upToken);

解決方案

Amazon S3 協議

Amazon 是最早提供對象存儲服務 的廠商,制定文件存儲相關的業內標準,這意味著只需要實現 S3 協議即可接入兼容此協議的文件存儲廠商和中間件。當然 S3 協議不僅僅是技術實現要求標準,對於可用性等都有具體的要求。

兼容 S3 協議國內雲廠商

名稱 地址
阿里雲 https://www.aliyun.com
華為雲 https://www.huaweicloud.com
騰訊雲 https://cloud.tencent.com
七牛雲 https://www.qiniu.com
金山雲 https://www.ksyun.com

如何使用

  • 引入依賴。 引入此依賴,無需在引入雲廠商 SDK
<dependency>
    <groupId>com.pig4cloud.plugin</groupId>
    <artifactId>oss-spring-boot-starter</artifactId>
    <version>0.0.1</version>
</dependency>
  • 配置文件存儲
oss:
  path-style-access: false    #請求路徑是否 XXX/{bucketName}
  endpoint: s3-cn-east-1.qiniucs.com
  access-key: xxx    # 雲廠商提供的key
  secret-key: xxx    # 雲廠商提供的密鑰
  bucketName: pig4cloud     # 上文創建的桶名稱
  • 操作

@Autowire
private final OssTemplate ossTemplate;

ossTemplate.putObject(CommonConstants.BUCKET_NAME, fileName, file.getInputStream());

支持 MINIO 等自建文件存儲

  • 創建 minio
docker run -p 9000:9000 --name minio1 \
  -e "MINIO_ACCESS_KEY=lengleng" \
  -e "MINIO_SECRET_KEY=lengleng" \
  minio/minio server /data
  • 配置 minio 參數
# 文件系統
oss:
  path-style-access: true
  endpoint: http://IP:9000
  access-key: lengleng
  secret-key: lengleng
  bucketName: lengleng
  • 使用 OssTemplate 上傳即可

源碼地址:

https://github.com/pig-mesh/oss-spring-boot-starter 歡迎 fork 擴展

項目推薦: Spring Cloud 、Spring Security OAuth2的RBAC權限管理系統 歡迎關注

Leave a Reply

Your email address will not be published. Required fields are marked *