package com.monkeylessey.file.properties;
|
|
import com.aliyun.oss.OSS;
|
import com.aliyun.oss.OSSClientBuilder;
|
import com.monkeylessey.exception.ConfigErrorException;
|
import lombok.Data;
|
import org.springframework.beans.factory.InitializingBean;
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Configuration;
|
import org.springframework.util.StringUtils;
|
|
/**
|
* @author 29443
|
* @date 2022/4/23
|
*/
|
@Data
|
@Configuration
|
@ConfigurationProperties(prefix = "oss")
|
public class OssProperties implements InitializingBean {
|
|
/**
|
* 上传文件需要的地域节点
|
*/
|
private String endpoint;
|
|
/**
|
* 获取sts临时访问令牌需要的地域节点
|
*/
|
private String stsEndpoint;
|
|
private String bucketName;
|
|
private String AccessKeyId;
|
|
private String AccessKeySecret;
|
|
/**
|
* 角色ARN
|
*/
|
private String roleArn;
|
|
/**
|
* 角色权限策略
|
*/
|
private String policy;
|
|
/**
|
* 自定义角色会话名称,用于区分不同的令牌,可随便填写
|
*/
|
private String roleSessionName;
|
|
/**
|
* 临时令牌的有效期,秒
|
*/
|
private Long stsExpireTime;
|
|
/**
|
* 访问url的有效期,秒(默认3600s,最大32400s)
|
*/
|
private Long urlExpireTime;
|
|
/**
|
* 获取oss客户端实例,因为后端是安全的,所以不需要使用sts,直接用RAM用户的accessKeyId和accessKeySecret构建oss客户端
|
*
|
* @return
|
*/
|
@Bean
|
public OSS ossClient() {
|
OSS client = new OSSClientBuilder().build(this.endpoint,
|
this.AccessKeyId,
|
this.AccessKeySecret
|
);
|
return client;
|
}
|
|
@Override
|
public void afterPropertiesSet() throws Exception {
|
checkStringProperties(this.endpoint, "请配置OSS 地域节点");
|
checkStringProperties(this.stsEndpoint, "请配置OSS sts地域节点");
|
checkStringProperties(this.bucketName, "请配置OSS bucket名称");
|
checkStringProperties(this.AccessKeyId, "请配置OSS AccessKeyId");
|
checkStringProperties(this.AccessKeySecret, "请配置OSS AccessKeySecret");
|
checkStringProperties(this.roleArn, "请配置OSS 角色ARN");
|
checkStringProperties(this.roleSessionName, "请配置OSS 角色会话名称");
|
checkLongProperties(this.stsExpireTime, 43200L, 900L, "临时令牌过期时间在900-43200秒之间");
|
checkLongProperties(this.urlExpireTime, Long.MAX_VALUE, 0L, "签名URL过期时间在0-Long.MAX_VALUE之间");
|
}
|
|
/**
|
* 检查配置不能为空
|
*
|
* @param property
|
* @param errMsg
|
*/
|
private void checkStringProperties(String property, String errMsg) {
|
if (!StringUtils.hasText(property)) {
|
throw new ConfigErrorException(errMsg);
|
}
|
}
|
|
/**
|
* 检查配置不能为空
|
*
|
* @param property
|
* @param errMsg
|
*/
|
private void checkLongProperties(Long property, Long max, Long min, String errMsg) {
|
if (property == null) {
|
throw new ConfigErrorException(errMsg);
|
}
|
if (property < min || property > max) {
|
throw new ConfigErrorException(errMsg);
|
}
|
}
|
}
|