SpringBoot整合华为云OBS

本文档介绍了如何在Java中实现华为云OBS对象存储服务的功能,包括文件上传、授权、临时上传授权、文件删除等操作。通过引入华为云OBS的Java SDK,并配置相应的应用程序属性,可以轻松地在应用程序中集成OBS服务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   一、参考项

华为云 OBS(官网): 对象存储服务OBS官网_海量安全高可靠_数据云存储解决方案-华为云
OBS SDK for Java(官网): SDK下载_对象存储服务 OBS_Java_华为云

三、引入Pom文件

<!-- https://mvnrepository.com/artifact/com.huaweicloud/esdk-obs-java -->
<dependency>
    <groupId>com.huaweicloud</groupId>
    <artifactId>esdk-obs-java</artifactId>
    <version>3.21.12</version>
</dependency>

二、定义抽象类

public abstract class BaseObjectStorage {

    /**
     * 上传文件
     *
     * @param pathAndName
     * @param file
     */
    public abstract void upload(String pathAndName, File file);

    /**
     * 授权
     *
     * @param pathAndName
     * @param time
     * @return
     */
    public abstract String authorize(String pathAndName, long time);

    /**
     * 授权(路径全)
     *
     * @param pathAndName
     * @param time
     * @return
     */
    public abstract String authorizeAllName(String pathAndName, long time);

    /**
     * 临时上传文件授权
     *
     * @param dir
     * @return
     */
    public abstract Map<String, Object> tokens(String dir);

    /**
     * 删除文件
     *
     * @param pathAndName
     */
    public abstract void deleteFile(String pathAndName);

}

三、OSS实现类

package cn.xhh.xhh.core.objectstorage;

import com.google.common.collect.Maps;
import com.obs.services.ObsClient;
import com.obs.services.model.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class ObsObjectStorage extends BaseObjectStorage {

  @Data
  @Component
  @ConfigurationProperties(prefix = "obs")
  public static class ObsInfo {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String rootDirectory;
    private String wgImage;
  }

  @Autowired
  private ObsInfo obsInfo;

  @Override
  public void upload(String pathAndName, File file) {
    ObsClient obsClient = new ObsClient(obsInfo.accessKeyId,
        obsInfo.accessKeySecret, obsInfo.endpoint);
    try {
      obsClient.putObject(obsInfo.bucketName, obsInfo.rootDirectory + pathAndName, file);
    } finally {
      try {
        obsClient.close();
      } catch (IOException e) {
      }
    }
  }

  @Override
  public String authorize(String pathAndName, long time) {
    ObsClient obsClient = new ObsClient(obsInfo.accessKeyId,
        obsInfo.accessKeySecret, obsInfo.endpoint);
    try {
      String path = obsInfo.rootDirectory + pathAndName;
      boolean doesObjectExist = obsClient.doesObjectExist(obsInfo.bucketName, path);
      if (!doesObjectExist) {
        path = obsInfo.wgImage;
      }
      TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, time);
      request.setBucketName(obsInfo.bucketName);
      request.setObjectKey(path);
      TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
      String url = response.getSignedUrl();
      return url;
    } finally {
      try {
        obsClient.close();
      } catch (IOException e) {
      }
    }
  }

  @Override
  public String authorizeAllName(String pathAndName, long time) {
    ObsClient obsClient = new ObsClient(obsInfo.accessKeyId,
        obsInfo.accessKeySecret, obsInfo.endpoint);
    try {
      String path = pathAndName;
      TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, time);
      request.setBucketName(obsInfo.bucketName);
      request.setObjectKey(path);
      TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
      String url = response.getSignedUrl();
      return url;
    } finally {
      try {
        obsClient.close();
      } catch (IOException e) {
      }
    }
  }

  @Override
  public Map<String, Object> tokens(String dir) {
    Map<String, Object> result = Maps.newHashMap();
    ObsClient obsClient = new ObsClient(obsInfo.accessKeyId,
        obsInfo.accessKeySecret, obsInfo.endpoint);
    try {
      long expireTime = 60;
      PostSignatureRequest request = new PostSignatureRequest();
      Map<String, Object> formParams = new HashMap<String, Object>();
      formParams.put("x-obs-acl", "public-read");
      formParams.put("content-type", "text/plain");
      request.setFormParams(formParams);
      request.setExpires(expireTime);
      PostSignatureResponse response = obsClient.createPostSignature(request);
      result.put("storeType", "obs");
      result.put("storageType", "obs");
      result.put("AccessKeyId", obsInfo.accessKeyId);
      result.put("policy", response.getPolicy());
      result.put("signature", response.getSignature());
      result.put("x-obs-acl", "public-read");
      result.put("content-type", "text/plain");
      result.put("dir", dir);
      result.put("host", obsInfo.endpoint.split("://")[0] + "://" + obsInfo.bucketName + "."
          + obsInfo.endpoint.split("://")[1]);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        obsClient.close();
      } catch (IOException e) {
      }
    }
    return result;
  }

  @Override
  public void deleteFile(String pathAndName) {
    ObsClient obsClient = new ObsClient(obsInfo.accessKeyId,
        obsInfo.accessKeySecret, obsInfo.endpoint);
    try {
      obsClient.deleteObject(obsInfo.bucketName, obsInfo.rootDirectory + pathAndName);
    } finally {
      try {
        obsClient.close();
      } catch (IOException e) {
      }
    }
  }

}

四、application配置文件

objectstorage.type: obs
obs:
  endpoint: https://oss-cn-xhh.aliyuncs.com
  access-key-id: LTAI4GKXXXYuEzsXXXXyY63x
  access-key-secret: BXXXPwUVZr8XXXXjFMPjkw
  bucket-name: data
  root-directory: xhh/export/

### 华为云 DeepSeek API 调用教程 #### 1. 准备工作 为了成功调用华为云上的 DeepSeek API,需先完成必要的准备工作。这包括但不限于创建华为云账号并登录到控制台,在服务列表中找到 AI 开发平台 ModelArts 或者其他支持 DeepSeek 的服务平台,并开通相应的服务[^2]。 #### 2. 获取API密钥 进入华为云管理后台后,按照指引获取用于身份验证的 API Key 和 Secret Key 。这些信息对于后续发起请求至关重要,因为每次调用都需要携带正确的认证参数来证明使用者的身份合法性[^3]。 #### 3. 构建HTTP请求 构建 HTTP 请求时需要注意设置合适的 URL 地址以及方法类型(GET/POST),同时还要加入必需的头部字段如 `Content-Type` 设定为 `application/json` ,并将之前得到的 API 密钥通过特定方式嵌入至 Header 中以便于鉴权校验。具体URL可以参照官方提供的API文档中的说明[^1]。 ```python import requests from hashlib import sha256 import hmac import base64 import time def create_signature(secret_key, message): key = bytes(secret_key, 'UTF-8') msg = bytes(message, 'UTF-8') signature = hmac.new(key, msg, sha256).digest() return str(base64.b64encode(signature), 'utf-8') timestamp = int(time.time() * 1000) secret_key = "your_secret_key" access_key = "your_access_key" url = f"https://api.huaweicloud.com/v1/deepseek/inference?AccessKeyId={access_key}&Timestamp={timestamp}" headers = { 'content-type': 'application/json', } payload = {"input": "example input"} signature = create_signature(secret_key=secret_key, message=url) response = requests.post(url+f"&Signature={signature}", headers=headers, json=payload) print(response.json()) ``` 此段 Python 代码展示了如何利用 HMAC-SHA256 加密算法生成签名字符串,并将其附加到最终发送给服务器的 POST 请求链接后面作为查询参数的一部分;同时也示范了怎样组装基本的数据包体结构以满足接口对接的要求。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值