Skip to content

Java企业级项目集成阿里云OSS、短信SMS技术方案文档 ​

文档版本:V1.0 适用框架:SpringBoot 2.x / 3.x(单体/微服务通用) 定位:生产环境可用、高可用、规范封装、可直接落地 作者:资深Java架构师

文档包含:业务背景、架构设计、权限规范、依赖引入、配置绑定、工具封装、异常处理、熔断重试、安全规范、监控告警、常见故障排查。

目录 ​

  1. 概述
  2. 前置准备(阿里云控制台配置)
  3. 总体架构设计与设计原则
  4. Maven依赖引入
  5. 配置文件与配置绑定
  6. 阿里云OSS模块封装实现
  7. 阿里云短信SMS模块封装实现
  8. 通用稳定性方案(重试、熔断、限流、幂等)
  9. 安全规范(AccessKey防泄露、权限最小化)
  10. 日志、链路追踪、监控指标
  11. 业务层调用示例
  12. 全局异常处理器【补充】
  13. 数据库设计:短信发送记录表【补充】
  14. OSS前端PostPolicy直传实现【补充】
  15. 生产环境最佳实践
  16. 常见问题与故障排查
  17. 上线检查清单
  18. 后续扩展方向

1. 概述 ​

1.1 业务目标 ​

在Java后端系统统一接入两类阿里云OpenAPI能力:

  • OSS 对象存储:文件上传、下载、删除、生成临时访问URL、前端直传(PostPolicy);
  • SMS 短信服务:验证码、通知类短信发送、短信回执查询。

1.2 非功能性要求 ​

  1. 解耦:第三方SDK代码隔离,不侵入业务代码;面向接口编程,方便后期切换云厂商;
  2. 健壮:超时控制、异常分级捕获、重试策略、熔断降级;
  3. 安全:禁止硬编码AK,遵循最小权限RAM策略;
  4. 可观测:结构化日志、耗时统计、异常告警;
  5. 可扩展:支持多Bucket、多短信签名/模板动态扩展。

1.3 技术选型说明 ​

  • OSS:官方 aliyun-sdk-oss(V1稳定版,企业项目广泛使用)
  • SMS:阿里云OpenAPI SDK aliyun-java-sdk-dysmsapi
  • 容错:Resilience4j(SpringBoot3推荐,替代Hystrix)
  • 配置绑定:@ConfigurationProperties 外部化配置,区分开发/测试/生产环境

2. 前置准备(阿里云控制台操作) ​

2.1 RAM账号创建(严禁使用主账号AK) ​

  1. 创建RAM子用户,只开启OpenAPI访问;
  2. 授权策略:最小权限原则
    • OSS:仅授予指定Bucket上传/下载/删除权限,拒绝全量权限 AliyunOSSFullAccess;
    • SMS:授予 AliyunDysmsFullAccess 或自定义细粒度策略;
  3. 保存 AccessKeyID / AccessKeySecret,生产环境禁止明文放在配置文件。

2.2 OSS控制台 ​

  1. 创建Bucket;设置读写权限(推荐私有读写,业务通过签名URL访问);
  2. 配置跨域CORS(前端直传场景);
  3. 记录Endpoint、Bucket名称。

2.3 短信SMS控制台 ​

  1. 企业资质认证;
  2. 申请短信签名、短信模板,等待审核通过;
  3. 记录模板CODE、签名名称。

3. 总体架构设计与设计原则 ​

3.1 分层结构 ​

业务 Service

↓

【统一第三方门面接口】AliyunClientService

├─ OssFileService(文件操作接口)

└─ SmsService(短信发送接口)

↓

实现类(封装阿里云 SDK)

↓

Resilience4j 熔断 / 重试切面

↓

阿里云 SDK Client

xml
### 3.2 核心设计原则
1. **适配器模式**:抽象接口屏蔽第三方SDK API,更换云厂商仅替换实现;
2. **单例Client**:OSSClient、SMS Client全局单例,复用连接池,不要频繁创建销毁;
3. **异常隔离**:自定义业务异常,区分SDK网络异常、业务错误码、权限异常;
4. **职责分离**:工具类只做SDK调用,业务层控制幂等、限流、缓存;
5. **禁止在工具类写业务逻辑**(如验证码缓存、手机号校验放到业务层)。

## 4. Maven依赖
```xml
<!-- 阿里云OSS -->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.17.0</version>
</dependency>

<!-- 阿里云短信SMS -->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.6.0</version>
</dependency>

<!-- 配置绑定 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

<!-- 熔断重试 Resilience4j -->
<dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-spring-boot2</artifactId>
    <version>1.7.1</version>
</dependency>

<!-- Lombok、日志、JSON按需引入 -->

5. 配置文件与配置绑定 ​

5.1 application.yml ​

yaml
aliyun:
  # OSS配置
  oss:
    enable: true
    endpoint: oss-cn-hangzhou.aliyuncs.com
    access-key-id: ${ALIYUN_OSS_AK:}
    access-key-secret: ${ALIYUN_OSS_SK:}
    bucket-name: company-file-bucket
    # 客户端参数
    max-connections: 200
    socket-timeout: 30000
    connection-timeout: 10000
    # 临时URL过期时间(秒)
    presign-expire-seconds: 3600

  # 短信配置
  sms:
    enable: true
    access-key-id: ${ALIYUN_SMS_AK:}
    access-key-secret: ${ALIYUN_SMS_SK:}
    region-id: cn-hangzhou
    endpoint: dysmsapi.aliyuncs.com

# 熔断重试配置
resilience4j:
  retry:
    instances:
      aliyunOss:
        max-retry-attempts: 2
        wait-duration: 500
        enable-exponential-backoff: true
      aliyunSms:
        max-retry-attempts: 1
        wait-duration: 800
  circuitbreaker:
    instances:
      aliyunOss:
        sliding-window-size: 10
        failure-rate-threshold: 30
        wait-duration-in-open-state: 30000
      aliyunSms:
        sliding-window-size: 10
        failure-rate-threshold: 30
        wait-duration-in-open-state: 30000

✅ 最佳实践:生产环境使用环境变量注入 AK,不在 yml 明文存储。

5.2 OSS 配置属性类 ​

java
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Data
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOssProperties {
    private Boolean enable;
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private Integer maxConnections;
    private Integer socketTimeout;
    private Integer connectionTimeout;
    private Long presignExpireSeconds;
}

5.3 短信配置属性类 ​

java
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Data
@ConfigurationProperties(prefix = "aliyun.sms")
public class AliyunSmsProperties {
    private Boolean enable;
    private String accessKeyId;
    private String accessKeySecret;
    private String regionId;
    private String endpoint;
}

5.4 启动类开启配置绑定 ​

java
@SpringBootApplication
@EnableConfigurationProperties({AliyunOssProperties.class, AliyunSmsProperties.class})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

6. 阿里云 OSS 模块封装实现 ​

6.1 OSS 客户端自动配置 ​

java
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PreDestroy;

@Configuration
public class AliyunOssConfig {
    private final AliyunOssProperties ossProperties;
    private OSS ossClient;

    public AliyunOssConfig(AliyunOssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }

    @Bean(destroyMethod = "")
    public OSS ossClient() {
        if (!ossProperties.getEnable()) {
            return null;
        }
        ossClient = new OSSClientBuilder()
                .build(ossProperties.getEndpoint(),
                        ossProperties.getAccessKeyId(),
                        ossProperties.getAccessKeySecret());
        return ossClient;
    }

    @PreDestroy
    public void closeOssClient() {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }
}
java
package com.jd.mall.controller;

import com.jd.mall.result.Result;
import com.jd.mall.service.OssFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 阿里云OSS文件上传Controller
 * 管理端上传商品/品牌/SKU图片统一入口
 */
@Slf4j
@RestController
@RequestMapping("/thirdparty/oss")
@RequiredArgsConstructor
public class OssController {

    private final OssFileService ossFileService;

    /**
     * 图片上传(通用)
     * 请求: multipart/form-data
     * 参数: file=文件(必填), dir=目录前缀(可选 如 product/brand/sku)
     * 返回: { code, msg, data: "https://bucket.endpoint/product/xxx.jpg" }
     */
    @PostMapping("/upload")
    public Result<String> upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "dir", required = false, defaultValue = "mall") String dir
    ) {
        if (file == null || file.isEmpty()) {
            return Result.error(4001,"上传文件不能为空");
        }
        String original = file.getOriginalFilename();
        String ext = "";
        if (original != null && original.contains(".")) {
            ext = original.substring(original.lastIndexOf("."));
        }
        // 生成 objectKey: dir/yyyy/MM/dd/uuid.ext
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String objectKey = dir + "/"
                + sdf.format(new Date()) + "/"
                + UUID.randomUUID().toString().replace("-", "")
                + ext.toLowerCase();

        String url = ossFileService.uploadFile(objectKey, file);
        log.info("[OSS上传] original={}, size={}, url={}", original, file.getSize(), url);
        return Result.success(url);
    }

    /**
     * 删除OSS上的文件
     * @param objectKey oss对象key(不含域名),例如 mall/2024/01/01/xxx.jpg
     */
    @DeleteMapping("/{objectKey}")
    public Result remove(@PathVariable String objectKey) {
        try {
            ossFileService.deleteFile(objectKey);
            return Result.success(true);
        } catch (Exception e) {
            log.warn("[OSS删除失败] objectKey={}", objectKey, e);
            return Result.error(4002,"文件删除失败: " + e.getMessage());
        }
    }
}

6.2 业务接口定义 ​

java
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;

public interface OssFileService {
    /**
     * 文件上传
     * @param objectKey oss路径
     * @param file 文件
     * @return 访问URL
     */
    String uploadFile(String objectKey, MultipartFile file);

    /**
     * 流式上传
     */
    String uploadStream(String objectKey, InputStream inputStream);

    /**
     * 删除文件
     */
    void deleteFile(String objectKey);

    /**
     * 生成私有文件临时访问URL
     */
    String generatePresignUrl(String objectKey);
}

6.3 接口实现(核心封装,分级异常捕获) ​

java
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;
import java.io.InputStream;
import java.util.Date;

@Slf4j
@Service
@RequiredArgsConstructor
public class AliyunOssFileServiceImpl implements OssFileService {

    private final OSS ossClient;
    private final AliyunOssProperties ossProperties;
    public static final String CIRCUIT_NAME = "aliyunOss";

    @Override
    @Retry(name = CIRCUIT_NAME)
    @CircuitBreaker(name = CIRCUIT_NAME)
    public String uploadFile(String objectKey, MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            return uploadStream(objectKey, inputStream);
        } catch (Exception e) {
            log.error("[OSS上传失败] objectKey:{}", objectKey, e);
            throw new AliyunOssException("文件上传云存储失败", e);
        }
    }

    @Override
    @Retry(name = CIRCUIT_NAME)
    @CircuitBreaker(name = CIRCUIT_NAME)
    public String uploadStream(String objectKey, InputStream inputStream) {
        PutObjectRequest request = new PutObjectRequest(ossProperties.getBucketName(), objectKey, inputStream);
        try {
            ossClient.putObject(request);
            String url = buildPublicUrl(objectKey);
            log.info("[OSS上传成功] objectKey={}, url={}", objectKey, url);
            return url;
        } catch (OSSException oe) {
            log.error("[OSS服务异常] errorCode:{} msg:{}", oe.getErrorCode(), oe.getErrorMessage(), oe);
            throw new AliyunOssException("OSS服务调用异常:" + oe.getErrorMessage(), oe);
        } catch (Exception e) {
            log.error("[OSS上传未知异常] objectKey:{}", objectKey, e);
            throw new AliyunOssException("云存储上传异常", e);
        }
    }

    @Override
    @Retry(name = CIRCUIT_NAME)
    @CircuitBreaker(name = CIRCUIT_NAME)
    public void deleteFile(String objectKey) {
        ossClient.deleteObject(ossProperties.getBucketName(), objectKey);
        log.info("[OSS删除成功] objectKey={}", objectKey);
    }

    @Override
    @Retry(name = CIRCUIT_NAME)
    @CircuitBreaker(name = CIRCUIT_NAME)
    public String generatePresignUrl(String objectKey) {
        Date expireTime = new Date(System.currentTimeMillis() + ossProperties.getPresignExpireSeconds() * 1000);
        String url = ossClient.generatePresignedUrl(ossProperties.getBucketName(), objectKey, expireTime).toString();
        log.debug("[OSS生成临时URL] objectKey={}", objectKey);
        return url;
    }

    private String buildPublicUrl(String objectKey) {
        return String.format("https://%s.%s/%s",
                ossProperties.getBucketName(), ossProperties.getEndpoint(), objectKey);
    }
}

6.4 自定义 OSS 异常 ​

java
public class AliyunOssException extends RuntimeException {
    public AliyunOssException(String message) {
        super(message);
    }
    public AliyunOssException(String message, Throwable cause) {
        super(message, cause);
    }
}

7. 阿里云短信 SMS 模块封装实现 ​

7.1 SMS 客户端配置 ​

java
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AliyunSmsConfig {
    private final AliyunSmsProperties smsProperties;

    public AliyunSmsConfig(AliyunSmsProperties smsProperties) {
        this.smsProperties = smsProperties;
    }

    @Bean
    public Client smsClient() throws Exception {
        if (!smsProperties.getEnable()) {
            return null;
        }
        Config config = new Config()
                .setAccessKeyId(smsProperties.getAccessKeyId())
                .setAccessKeySecret(smsProperties.getAccessKeySecret())
                .setEndpoint(smsProperties.getEndpoint());
        return new Client(config);
    }
}

7.2 短信入参 DTO ​

java
import lombok.Data;
import javax.validation.constraints.NotBlank;

@Data
public class SmsSendDTO {
    @NotBlank(message = "手机号不能为空")
    private String phoneNumber;
    @NotBlank(message = "短信签名不能为空")
    private String signName;
    @NotBlank(message = "模板CODE不能为空")
    private String templateCode;
    // 模板参数JSON字符串 {"code":"123456"}
    private String templateParam;
}

7.3 短信服务接口 ​

java
public interface SmsService {
    /**
     * 发送短信
     */
    void sendSms(SmsSendDTO dto);
}

7.4 短信实现类 ​

重要提醒:短信为计费接口,重复调用会重复扣费;网络超时不建议自动重试,优先业务层幂等控制。

java
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class AliyunSmsServiceImpl implements SmsService {
    private final Client smsClient;
    public static final String CIRCUIT_NAME = "aliyunSms";

    @Override
    @CircuitBreaker(name = CIRCUIT_NAME)
    public void sendSms(SmsSendDTO dto) {
        SendSmsRequest request = new SendSmsRequest()
                .setPhoneNumbers(dto.getPhoneNumber())
                .setSignName(dto.getSignName())
                .setTemplateCode(dto.getTemplateCode())
                .setTemplateParam(dto.getTemplateParam());
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            SendSmsResponse response = smsClient.sendSmsWithOptions(request, runtime);
            String code = response.getBody().getCode();
            if (!"OK".equals(code)) {
                log.error("[短信发送失败] phone={}, code={}, msg={}",
                        dto.getPhoneNumber(), code, response.getBody().getMessage());
                throw new AliyunSmsException("短信发送失败:" + response.getBody().getMessage());
            }
            log.info("[短信发送成功] phone={}, templateCode={}", dto.getPhoneNumber(), dto.getTemplateCode());
        } catch (Exception e) {
            log.error("[短信调用异常] phone={}", dto.getPhoneNumber(), e);
            throw new AliyunSmsException("短信服务调用异常", e);
        }
    }
}

7.5 短信自定义异常 ​

java
public class AliyunSmsException extends RuntimeException {
    public AliyunSmsException(String message) {
        super(message);
    }
    public AliyunSmsException(String message, Throwable cause) {
        super(message, cause);
    }
}

8. 通用稳定性方案规范 ​

8.1 重试策略规范 ​

  1. OSS:允许 2 次重试(文件上传瞬时网络抖动);
  2. 短信 SMS:SDK 层关闭自动重试,业务层自行控制幂等,防止重复扣费;
  3. 只对网络超时、连接异常重试;权限错误、参数错误禁止重试。

8.2 熔断策略 ​

  • 异常率阈值 30%;熔断窗口 30s;
  • 熔断打开后,快速失败,避免持续打垮第三方 API。

8.3 业务层幂等与限流(必须在 Service 层实现) ​

  1. 短信验证码:Redis 限流,60s 内同一手机号最多发送 1 次;
  2. 使用唯一业务单号做幂等,防止前端重复点击;
  3. 不要依赖阿里云接口做幂等,短信接口本身不支持幂等。

9. 安全规范(生产红线) ​

  1. 禁止硬编码 AK;
  2. 使用 RAM 子账号,最小权限;
  3. Bucket 推荐私有读写,业务使用签名 URL;
  4. 日志脱敏:手机号只保留首尾,禁止打印完整 AK;
  5. 定期轮换 AccessKey;
  6. 前端直传 OSS 必须使用 PostPolicy + 服务端回调,禁止前端携带 AK。

10. 日志、链路追踪、监控 ​

  1. 所有第三方调用日志携带 traceId(MDC);
  2. 记录:调用耗时、返回码、异常堆栈;
  3. 监控指标:
    • OSS:上传成功率、平均耗时、异常次数;
    • SMS:短信发送成功率、失败类型统计;
  4. 告警:第三方接口异常率持续走高触发邮件 / 钉钉告警。

11. 业务层调用示例 ​

java
@Service
public class FileBusinessService {
    private final OssFileService ossFileService;
    private final SmsService smsService;

    // 文件上传
    public String uploadAvatar(MultipartFile file) {
        String objectKey = "avatar/" + UUID.randomUUID() + getSuffix(file.getOriginalFilename());
        return ossFileService.uploadFile(objectKey, file);
    }

    // 发送验证码
    public void sendCode(String phone, String code) {
        // 1. Redis限流校验
        // 2. 组装参数
        SmsSendDTO dto = new SmsSendDTO();
        dto.setPhoneNumber(phone);
        dto.setSignName("XX公司");
        dto.setTemplateCode("SMS_12345678");
        dto.setTemplateParam(JSON.toJSONString(Map.of("code", code)));
        smsService.sendSms(dto);
    }
}

12. 全局异常处理器【补充】 ​

统一捕获阿里云自定义异常,返回项目标准响应结构

java
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {

    // 阿里云OSS异常
    @ResponseBody
    @ExceptionHandler(AliyunOssException.class)
    public Result<?> handleOssException(AliyunOssException e) {
        log.error("OSS异常:", e);
        return Result.fail(5001, e.getMessage());
    }

    // 阿里云短信异常
    @ResponseBody
    @ExceptionHandler(AliyunSmsException.class)
    public Result<?> handleSmsException(AliyunSmsException e) {
        log.error("短信异常:", e);
        return Result.fail(5002, e.getMessage());
    }
}

Result 为项目统一返回封装实体,根据项目现有结构自行适配。

13. 数据库设计:短信发送记录表 SQL【补充】 ​

sql
CREATE TABLE sys_sms_record (
    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
    phone_number VARCHAR(20) NOT NULL COMMENT '手机号',
    sign_name VARCHAR(50) NOT NULL COMMENT '短信签名',
    template_code VARCHAR(60) NOT NULL COMMENT '短信模板CODE',
    template_param VARCHAR(1000) COMMENT '模板参数JSON',
    biz_id VARCHAR(128) COMMENT '阿里云回执BizId',
    send_status TINYINT DEFAULT 0 COMMENT '0待发送 1发送成功 2发送失败',
    remark VARCHAR(500) COMMENT '备注/失败原因',
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_phone (phone_number),
    INDEX idx_create_time (create_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='短信发送记录表';

14. OSS 前端 PostPolicy 直传实现【补充】 ​

适用场景:前端直接上传文件到 OSS,不经过后端中转,降低服务器带宽压力

  1. 后端接口生成 Policy 签名
  2. 前端携带 Policy、签名直传 OSS
  3. 可选配置 OSS 回调地址,上传完成通知后端保存文件信息
java
/**
 * 获取OSS前端直传Policy
 */
public OssPolicyVO getOssPostPolicy() {
    String expire = ISO8601Utils.format(new Date(System.currentTimeMillis() + 30 * 60 * 1000));
    String condition = "[[\"starts-with\",\"$key\",\"upload/\"]]";
    String policyText = "{\"expiration\":\"" + expire + "\",\"conditions\":" + condition + "}";
    String policy = Base64.getEncoder().encodeToString(policyText.getBytes(StandardCharsets.UTF_8));
    String signature = BinaryUtil.calculateHmacSHA1(policy, ossProperties.getAccessKeySecret());

    OssPolicyVO vo = new OssPolicyVO();
    vo.setAccessKeyId(ossProperties.getAccessKeyId());
    vo.setHost("https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint());
    vo.setPolicy(policy);
    vo.setSignature(signature);
    return vo;
}

15. 生产环境最佳实践清单 ​

  • 区分 dev/test/prod 三套阿里云资源;
  • 环境变量注入 AK,配置文件不存储密钥;
  • 服务启动增加 Bean 校验,AK 缺失主动抛出启动异常;
  • 大文件上传使用分片上传接口;
  • 短信业务增加发送记录数据表,持久化发送日志;
  • 对接短信回执,判断是否真正送达。

16. 常见问题与故障排查 ​

  1. OSS NoSuchBucket / AccessDenied:RAM 权限不足、Bucket 名称 / 区域不匹配;
  2. 短信 isv.BUSINESS_LIMIT_CONTROL:触发阿里云 QPS 限流,业务层增加限流;
  3. 客户端连接耗尽:OSSClient 全局单例,不要每次 new;
  4. 临时 URL 过期时间溢出:不要设置超过 2038 年;
  5. 跨域报错:OSS 控制台配置 CORS 允许 Origin 与 Method。

17. 上线检查清单 ​

  1. RAM 子账号权限最小化验证
  2. AK 禁止明文存储,使用环境变量 / 配置中心
  3. Bucket 权限、CORS 配置核对
  4. 短信签名、模板审核状态确认
  5. 熔断、重试参数预调优
  6. 日志脱敏校验
  7. 异常场景测试(网络断开、权限失效)

18. 后续扩展方向(可选) ​

  1. 引入 MQ 异步发送短信,削峰解耦;
  2. 实现 OSS 分片上传、断点续传;
  3. 接入 STS 临时凭证,前端直传场景;
  4. 多云厂商适配(阿里云 + 腾讯云 OSS)