「一站式」兼容全部雲廠商文件存儲Spring Boot 實現

背景

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

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

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

阿里雲

// 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 協議不單單是技術實現要求標準,對於可用性等都有具體的要求。spring

兼容 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 上傳便可

源碼地址:docker

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

image

相關文章
相關標籤/搜索