当前位置:   article > 正文

OSS存储服务快速入门+分布式OSS存储

oss存储

目录

简介

1、什么是OSS呢?

2、aliyun的accessKey

 3、OSS存储服务

快速开始

1、引入依赖

2、单体架构

3、分布式架构

3.1、在common模块中配置yml文件

3.2、common模块创建对应的实体类,并引入yml中的数据

3.3、common模块创建OSSUtil工具类

3.4、在web模块中引入application-comm.yml

3.5、测试


简介

1、什么是OSS呢?

阿里云控制台首页 (aliyun.com) 或者百度所有aliyun

「OSS」的英文全称是Object Storage Service,翻译成中文就是「对象存储服务」,官方一点解释就是对象存储是一种使用HTTP API存储和检索非结构化数据和元数据对象的工具。

白话文解释就是将系统所要用的文件上传到云硬盘上,该云硬盘提供了文件下载、上传等一列服务,这样的服务以及技术可以统称为OSS,业内提供OSS服务的厂商很多,知名常用且成规模的蓝队云等。

不但有aliyun的OSS存储服务,还有 腾讯云的OBS,腾讯云的COS等,都是可以通过SDK接口实现的。

2、aliyun的accessKey

 创建好自己的accessKey一定要记好你的Key和Secret

 3、OSS存储服务

 

 创建一个自己的桶(Bucket) ,创建完成之后,点击你自己的桶名称,

点击概览,最后就会有一个endipint的域点 

快速开始

OSS存储我分两个模块来讲解,第一种是单体架构,可以直接使用的快速开发,第二种是公司常用的分布式架构的OSS存储

1、引入依赖

  1. <!-- OSS对象存储-->
  2. <dependency>
  3. <groupId>com.aliyun.oss</groupId>
  4. <artifactId>aliyun-sdk-oss</artifactId>
  5. <version>3.10.2</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>commons-fileupload</groupId>
  9. <artifactId>commons-fileupload</artifactId>
  10. <version>1.3.3</version>
  11. </dependency>

2、单体架构

  1. package com.dongyimai.util;
  2. import com.aliyun.oss.ClientException;
  3. import com.aliyun.oss.OSS;
  4. import com.aliyun.oss.OSSClientBuilder;
  5. import com.aliyun.oss.OSSException;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import java.io.IOException;
  10. import java.io.Serializable;
  11. import java.time.LocalDate;
  12. import java.util.UUID;
  13. public class OSSUtil implements Serializable {
  14. public static String uploadFile(MultipartFile file) {
  15. // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
  16. //在上述csdn中的OSS存储服务介绍了如何获取下面的4个信息
  17. String endpoint = "自己存储服务的域点";
  18. // 强烈建议不要把访问凭证保存到工程代码里,否则可能导致访问凭证泄露,威胁您账号下所有资源的安全。本代码示例以从环境变量中获取访问凭证为例。运行本代码示例之前,请先配置环境变量。
  19. String accessKeyId = "自己的accessKey";
  20. String accessKeySecret = "自己的accessKeySecret";
  21. // 填写Bucket名称,例如examplebucket。
  22. String bucketName ="自己的桶";
  23. // 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
  24. //防止重复覆盖设置随机数
  25. String uuid= UUID.randomUUID().toString().replaceAll("-","");
  26. // String objectName = imgPath;
  27. //文件名就变为: 随机数+a.jpg
  28. String fileName=uuid+file.getOriginalFilename();
  29. String dataPath = LocalDate.now().toString();
  30. String path = dataPath.replaceAll("-", "/");
  31. fileName=path+"/"+fileName;
  32. // 创建OSSClient实例。
  33. OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
  34. try {
  35. ossClient.putObject(bucketName, fileName,file.getInputStream());
  36. //返回的图片路径 https://+bucketName名称+.+endpoint+objectName+/+fileName
  37. String url="https://"+bucketName+"."+endpoint+"/"+fileName;
  38. return url;
  39. } catch ( OSSException oe) {
  40. System.out.println("Caught an OSSException, which means your request made it to OSS, "
  41. + "but was rejected with an error response for some reason.");
  42. System.out.println("Error Message:" + oe.getErrorMessage());
  43. System.out.println("Error Code:" + oe.getErrorCode());
  44. System.out.println("Request ID:" + oe.getRequestId());
  45. System.out.println("Host ID:" + oe.getHostId());
  46. } catch ( ClientException ce) {
  47. System.out.println("Caught an ClientException, which means the client encountered "
  48. + "a serious internal problem while trying to communicate with OSS, "
  49. + "such as not being able to access the network.");
  50. System.out.println("Error Message:" + ce.getMessage());
  51. } catch (IOException e) {
  52. e.printStackTrace();
  53. } finally {
  54. if (ossClient != null) {
  55. ossClient.shutdown();
  56. }
  57. }
  58. return null;
  59. }
  60. }

使用到单体架构,就直接当一个util文件使用即可。

下图就是上述代码,忽略即可

 

3、分布式架构

我的项目结构:将common模块作为工具模块,web启动类模块引入common依赖

 

 

3.1、在common模块中配置yml文件

application-comm.yml

  1. #当前的yaml的名称为:application-comm.yml
  2. oss:
  3. endpoint: 自己的域点
  4. accessKeyId: 自己的accessKeyId
  5. accessKeySecret: 自己的accesskeySecret
  6. bucketName: 自己的桶

3.2、common模块创建对应的实体类,并引入yml中的数据

  1. package com.dongyimai.util;
  2. import org.springframework.beans.factory.InitializingBean;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.boot.context.properties.ConfigurationProperties;
  5. import org.springframework.stereotype.Component;
  6. import java.io.Serializable;
  7. @Component
  8. @ConfigurationProperties(prefix = "oss")
  9. public class ConstantPropertiesUtils implements Serializable , InitializingBean {
  10. //读取配置文件的内容
  11. private String endpoint;
  12. private String accessKeyId;
  13. private String accessKeySecret;
  14. private String bucketName;
  15. public String getEndpoint() {
  16. return endpoint;
  17. }
  18. public void setEndpoint(String endpoint) {
  19. this.endpoint = endpoint;
  20. }
  21. public String getAccessKeyId() {
  22. return accessKeyId;
  23. }
  24. public void setAccessKeyId(String accessKeyId) {
  25. this.accessKeyId = accessKeyId;
  26. }
  27. public String getAccessKeySecret() {
  28. return accessKeySecret;
  29. }
  30. public void setAccessKeySecret(String accessKeySecret) {
  31. this.accessKeySecret = accessKeySecret;
  32. }
  33. public String getBucketName() {
  34. return bucketName;
  35. }
  36. public void setBucketName(String bucketName) {
  37. this.bucketName = bucketName;
  38. }
  39. @Override
  40. public String toString() {
  41. return "ConstantPropertiesUtils{" +
  42. "endpoint='" + endpoint + '\'' +
  43. ", accessKeyId='" + accessKeyId + '\'' +
  44. ", accessKeySecret='" + accessKeySecret + '\'' +
  45. ", bucketName='" + bucketName + '\'' +
  46. '}';
  47. }
  48. //定义公共静态常量
  49. public static String END_POINT;
  50. public static String ACCESS_KEY_ID;
  51. public static String ACCESS_KEY_SECRET;
  52. public static String BUCKET_NAME;
  53. //在当前文件加载之后执行该方法
  54. //这个方法的意义就是:将已经被加载好的属性设置到静态常亮中,方便调用
  55. @Override
  56. public void afterPropertiesSet() throws Exception {
  57. END_POINT = endpoint;
  58. ACCESS_KEY_ID = accessKeyId;
  59. ACCESS_KEY_SECRET = accessKeySecret;
  60. BUCKET_NAME = bucketName;
  61. }
  62. }

注意:使用@ConfigurationProperties(prefix = "XXX")时,在springboot或者spring项目启动之后才会加载执行!

3.3、common模块创建OSSUtil工具类

  1. package com.dongyimai.util;
  2. import com.aliyun.oss.ClientException;
  3. import com.aliyun.oss.OSS;
  4. import com.aliyun.oss.OSSClientBuilder;
  5. import com.aliyun.oss.OSSException;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import java.io.IOException;
  10. import java.io.Serializable;
  11. import java.time.LocalDate;
  12. import java.util.UUID;
  13. public class OSSUtil implements Serializable {
  14. public static String uploadFile(MultipartFile file) {
  15. // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
  16. String endpoint = ConstantPropertiesUtils.END_POINT;
  17. // 强烈建议不要把访问凭证保存到工程代码里,否则可能导致访问凭证泄露,威胁您账号下所有资源的安全。本代码示例以从环境变量中获取访问凭证为例。运行本代码示例之前,请先配置环境变量。
  18. String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
  19. String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
  20. // 填写Bucket名称,例如examplebucket。
  21. String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
  22. // 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
  23. //防止重复覆盖设置随机数
  24. String uuid= UUID.randomUUID().toString().replaceAll("-","");
  25. // String objectName = imgPath;
  26. //文件名就变为: 随机数+a.jpg
  27. String fileName=uuid+file.getOriginalFilename();
  28. String dataPath = LocalDate.now().toString();
  29. String path = dataPath.replaceAll("-", "/");
  30. fileName=path+"/"+fileName;
  31. // 创建OSSClient实例。
  32. OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
  33. try {
  34. ossClient.putObject(bucketName, fileName,file.getInputStream());
  35. //返回的图片路径 https://+bucketName名称+.+endpoint+objectName+/+fileName
  36. String url="https://"+bucketName+"."+endpoint+"/"+fileName;
  37. return url;
  38. } catch ( OSSException oe) {
  39. System.out.println("Caught an OSSException, which means your request made it to OSS, "
  40. + "but was rejected with an error response for some reason.");
  41. System.out.println("Error Message:" + oe.getErrorMessage());
  42. System.out.println("Error Code:" + oe.getErrorCode());
  43. System.out.println("Request ID:" + oe.getRequestId());
  44. System.out.println("Host ID:" + oe.getHostId());
  45. } catch ( ClientException ce) {
  46. System.out.println("Caught an ClientException, which means the client encountered "
  47. + "a serious internal problem while trying to communicate with OSS, "
  48. + "such as not being able to access the network.");
  49. System.out.println("Error Message:" + ce.getMessage());
  50. } catch (IOException e) {
  51. e.printStackTrace();
  52. } finally {
  53. if (ossClient != null) {
  54. ossClient.shutdown();
  55. }
  56. }
  57. return null;
  58. }
  59. }

3.4、在web模块中引入application-comm.yml

因为涉及到两个模块时,当主启动类模块加载后,他的application.yml配置文件会覆盖掉子模块common中的application.yml,所以,我们给common模块中的yml改名称 applicaiton-comm.yml然后让主启动类application.yml模块中的yml引入即可:只引入-后边的名称就行

  1. spring:
  2. profiles:
  3. include: comm

3.5、测试

  1. @PostMapping("/upload")
  2. public ResultSet<String> upload( MultipartFile file){
  3. System.out.println("file="+file);
  4. String s = OSSUtil.uploadFile(file);
  5. //会获取到一个存储到OSS中的路径连接,可以直接通过百度查看图片
  6. System.out.println(s);
  7. return ResultSet.successData(s);
  8. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/379451
推荐阅读
相关标签
  

闽ICP备14008679号

        
cppcmd=keepalive&