Spring boot 阿里云 OSS 连接

1. 创建maven工程
    
2. pom.xml 添加 oss sdk

 <dependency>
      <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>3.8.0</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>

注意:aliyun-sdk-oss 默认没有包含 commons-logging,需要手动添加3. 定义obs实体类

import lombok.Data;

@Data
public class ObjectLink {

  private String operatorType;

  private String objectEndpoint;

  private String objectBucket;

  private String objectAk;

  private String objectSk;
}

5. 创建 OBSObjectUtil 类


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class OSSObjectUtil {

  static public Logger logger = LoggerFactory.getLogger(OSSObjectUtil.class);

  static public boolean connect(ObjectLink params) {

    // Endpoint以杭州为例,其它Region请按实际情况填写。
    String endpoint = params.getObjectEndpoint();

    // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
    String accessKeyId = params.getObjectAk();
    String accessKeySecret = params.getObjectSk();
    String bucketName = params.getObjectBucket();

    // 创建OSSClient实例。
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    if(ossClient == null){
      return false;
    }

    boolean isExist = false;
    if(ossClient.doesBucketExist(bucketName)){
      isExist = true;
    }

    // 关闭OSSClient。
    ossClient.shutdown();


    return  isExist;
  }

5. 创建main调用OBSObjectUtil 测试


public static void main(String args[]) {
  //https://help.aliyun.com/document_detail/32011.html?spm=a2c4g.11186623.6.766.4b6b63282a4WTf
  ObjectLink link = new ObjectLink();
  boolean b = OSSObjectUtil.connect(link);

  System.out.println("Hello World!");
}

参考:https://help.aliyun.com/document_detail/32011.html?spm=a2c4g.11186623.6.766.4b6b63282a4WTf

发布了220 篇原创文章 · 获赞 16 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/zhanggqianglovec/article/details/103880560