腾讯云COS代码集
2022-06-27 本文已影响0人
AC编程
一、配置类
@Data
@Component
@ConfigurationProperties(prefix="tencent-cos")
public class CosConfig {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private Integer durationSeconds;
private String regionId;
private String appId;
private String roleArn;
}
二、Service
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.region.Region;
import com.qimiao.qm.common.core.exceptions.QiMiaoException;
import com.qimiao.qm.oss.config.CosConfig;
import com.alanchen.oss.dto.OssSecurityTokenDTO;
import com.alanchen.oss.service.CosStsService;
import com.tencent.cloud.CosStsClient;
import com.tencent.cloud.Policy;
import com.tencent.cloud.Response;
import com.tencent.cloud.Statement;
import com.tencent.cloud.cos.util.Jackson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.net.URL;
import java.util.TreeMap;
@Slf4j
@Service
public class CosStsServiceImpl implements CosStsService {
@Resource
private CosConfig cosConfig;
@Value("${spring.profiles.active}")
private String active;
private String getActiveInfo(){
if("prod".equals(active)){
return active;
}
return "test";
}
/**
* 文档:
* https://github.com/tencentyun/qcloud-cos-sts-sdk/blob/master/java/src/test/java/com/tencent/cloud/CosStsClientTest.java
*
* @return
*/
@Override
public OssSecurityTokenDTO getMemberSecurityToken(Long memberId) {
TreeMap<String, Object> config = new TreeMap<>();
try {
String appId = cosConfig.getAppId();
String region = cosConfig.getRegionId();
config.put("secretId", cosConfig.getAccessKeyId());
config.put("secretKey", cosConfig.getAccessKeySecret());
config.put("durationSeconds", cosConfig.getDurationSeconds());
config.put("region", region);
Policy policy = new Policy();
policy.setVersion("2.0");
Statement statement = new Statement();
statement.setEffect("allow");
statement.addActions(new String[]{
"name/cos:GetObject",
"name/cos:PutObject",
"name/cos:PostObject",
"name/cos:InitiateMultipartUpload",
"name/cos:ListMultipartUploads",
"name/cos:ListParts",
"name/cos:UploadPart",
"name/cos:CompleteMultipartUpload"
});
//样例:qcs::cos:ap-beijing:uid/1238423:bucketA-1238423/*
final String RESOURCE_FORMAT = "qcs::cos:%s:uid/%s:%s/%s";
statement.addResources(new String[]{
String.format(RESOURCE_FORMAT,
region, appId, "alanchen-" + getActiveInfo() + "-public-" + appId, "*"),
String.format(RESOURCE_FORMAT,
region, appId, "alanchen-" + getActiveInfo() + "-op-" + appId, "*"),
String.format(RESOURCE_FORMAT,
region, appId, "alanchen-" + getActiveInfo() + "-private-" + appId, "content/" + memberId + "/*"),
String.format(RESOURCE_FORMAT,region, appId, "alanchen-1303140934", "*")
});
policy.addStatement(statement);
config.put("policy", Jackson.toJsonPrettyString(policy));
Response response = CosStsClient.getCredential(config);
return toTokenDTO(response);
} catch (Exception e) {
log.error("ERROR:" + e.getMessage());
throw new QiMiaoException("获取会员cos-token失败");
}
}
@Override
public OssSecurityTokenDTO getToken() {
TreeMap<String, Object> config = new TreeMap<>();
try {
String appId = cosConfig.getAppId();
String region = cosConfig.getRegionId();
config.put("secretId", cosConfig.getAccessKeyId());
config.put("secretKey", cosConfig.getAccessKeySecret());
config.put("durationSeconds", cosConfig.getDurationSeconds());
config.put("region", region);
Policy policy = new Policy();
policy.setVersion("2.0");
Statement statement = new Statement();
statement.setEffect("allow");
statement.addActions(new String[]{"*"});
//样例:qcs::cos:ap-beijing:uid/1238423:bucketA-1238423/*
final String RESOURCE_FORMAT = "qcs::cos:%s:uid/%s:%s/%s";
statement.addResources(new String[]{
String.format(RESOURCE_FORMAT,
region, appId, "alanchen-" + getActiveInfo() + "-public-" + appId, "*"),
String.format(RESOURCE_FORMAT,
region, appId, "alanchen-" + getActiveInfo() + "-op-" + appId, "*"),
String.format(RESOURCE_FORMAT,
region, appId, "alanchen-" + getActiveInfo() + "-private-" + appId, "*"),
String.format(RESOURCE_FORMAT,region, appId, "alanchen-1303140934", "*")
});
policy.addStatement(statement);
config.put("policy", Jackson.toJsonPrettyString(policy));
Response response = CosStsClient.getCredential(config);
return toTokenDTO(response);
} catch (Exception e) {
log.error("ERROR:" + e.getMessage());
throw new QiMiaoException("获取公共cos-token失败");
}
}
/**
* objectName样例 :https://qm-test-private-1303140934.cos.ap-guangzhou.myqcloud.com/content/280/ddd.jpg
* host=qm-test-private-1303140934.cos.ap-guangzhou.myqcloud.com
* path=/content/280/ddd.jpg
*
* @param objectName
* @return
*/
@Override
public ObjectMetadata getObjectMetadata(String objectName) {
try {
URL url = new URL(objectName);
String host = url.getHost();
String path = url.getPath();
String bucketName = host.split("\\.")[0];
String key = path.replaceFirst("/", "");
COSClient cosclient = initCOSClient();
ObjectMetadata objectMetadata = cosclient.getObjectMetadata(bucketName, key);
cosclient.shutdown();
return objectMetadata;
} catch (Exception e) {
log.error(e.getMessage());
throw new QiMiaoException("获取cos元素失败");
}
}
private COSClient initCOSClient() {
COSCredentials cred = new BasicCOSCredentials(cosConfig.getAccessKeyId(), cosConfig.getAccessKeySecret());
ClientConfig clientConfig = new ClientConfig(new Region(cosConfig.getRegionId()));
COSClient cosclient = new COSClient(cred, clientConfig);
return cosclient;
}
private OssSecurityTokenDTO toTokenDTO(Response response) {
OssSecurityTokenDTO tokenDTO = new OssSecurityTokenDTO();
if (response != null) {
Long expiration = response.expiredTime - response.startTime;
tokenDTO.setAccessKeyId(response.credentials.tmpSecretId);
tokenDTO.setAccessKeySecret(response.credentials.tmpSecretKey);
tokenDTO.setSecurityToken(response.credentials.sessionToken);
tokenDTO.setExpiration(expiration);
tokenDTO.setGTime(response.startTime);
tokenDTO.setEndpoint(cosConfig.getEndpoint());
tokenDTO.setAppId(cosConfig.getAppId());
}
return tokenDTO;
}
}