import com.baiwang.customize.common.constants.BizPropConstant;
import com.baiwang.customize.common.enums.SystemIdEnum;
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.endpoint.EndpointBuilder;
import com.qcloud.cos.endpoint.SuffixEndpointBuilder;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.*;
/**
* @ClassName FileCloudStoreUtils
* @Description 对象存储
* @Author
* @Date 2022/4/7 15:56
*/
@Component
public class FileCloudStoreUtils {
private static final Logger logger = LoggerFactory.getLogger(FileCloudStoreUtils.class);
private static COSClient cosClientXIB ;
private static COSClient cosClientLCN ;
private static COSClient cosClientCYC ;
private FileCloudStoreUtils(){
logger.info("...... FileCloudStoreUtils init ......");
}
private static COSClient getCOSClient(String systemId) {
if(SystemIdEnum.XIB.name().equals(systemId)){
// 1 初始化用户身份信息
COSCredentials cred = new BasicCOSCredentials(BizPropConstant.XIB_SECRET_ID, BizPropConstant.XIB_SECRET_KEY);
// 2 设置 bucket 的地域
Region region = new Region(BizPropConstant.XIB_COS_REGION);
ClientConfig clientConfig = new ClientConfig(region);
if(BizPropConstant.XIB_SELF_COS_REGION){//自定义region bucketName+BizPropConstant.COS_REGION = eis-dev-1258237685+.ap-beijing+.myqcloud.com
EndpointBuilder endpointBuilder = new SuffixEndpointBuilder(BizPropConstant.XIB_COS_REGION);
clientConfig.setEndpointBuilder(endpointBuilder);
}
// 这里建议设置使用 https 协议
if(HttpProtocol.https.name().equals(BizPropConstant.XIB_HTTP_PROTOCOL)){
clientConfig.setHttpProtocol(HttpProtocol.https);
}else{
clientConfig.setHttpProtocol(HttpProtocol.http);
}
clientConfig.setMaxErrorRetry(3);//重试3次
// clientConfig.
// 3 生成 cos 客户端。
if (cosClientXIB == null) {
synchronized (FileCloudStoreUtils.class) {
if (cosClientXIB == null) {
cosClientXIB = new COSClient(cred, clientConfig);
logger.info("云对象客户端创建......");
}
}
}
return cosClientXIB;
}
if (SystemIdEnum.LCN.name().equals(systemId)){
// 1 初始化用户身份信息
COSCredentials cred = new BasicCOSCredentials(BizPropConstant.LCN_SECRET_ID, BizPropConstant.LCN_SECRET_KEY);
// 2 设置 bucket 的地域
Region region = new Region(BizPropConstant.LCN_COS_REGION);
ClientConfig clientConfig = new ClientConfig(region);
if(BizPropConstant.LCN_SELF_COS_REGION){//自定义region bucketName+BizPropConstant.COS_REGION = eis-dev-1258237685+.ap-beijing+.myqcloud.com
EndpointBuilder endpointBuilder = new SuffixEndpointBuilder(BizPropConstant.LCN_COS_REGION);
clientConfig.setEndpointBuilder(endpointBuilder);
}
// 这里建议设置使用 https 协议
if(HttpProtocol.https.name().equals(BizPropConstant.LCN_HTTP_PROTOCOL)){
clientConfig.setHttpProtocol(HttpProtocol.https);
}else{
clientConfig.setHttpProtocol(HttpProtocol.http);
}
clientConfig.setMaxErrorRetry(3);//重试3次
// clientConfig.
// 3 生成 cos 客户端。
if (cosClientLCN == null) {
synchronized (FileCloudStoreUtils.class) {
if (cosClientLCN == null) {
cosClientLCN = new COSClient(cred, clientConfig);
logger.info("云对象客户端创建......");
}
}
}
return cosClientLCN;
}
if (SystemIdEnum.CYC.name().equals(systemId)){
// 1 初始化用户身份信息
COSCredentials cred = new BasicCOSCredentials(BizPropConstant.CYC_SECRET_ID, BizPropConstant.CYC_SECRET_KEY);
// 2 设置 bucket 的地域
Region region = new Region(BizPropConstant.CYC_COS_REGION);
ClientConfig clientConfig = new ClientConfig(region);
if(BizPropConstant.CYC_SELF_COS_REGION){//自定义region bucketName+BizPropConstant.COS_REGION = eis-dev-1258237685+.ap-beijing+.myqcloud.com
EndpointBuilder endpointBuilder = new SuffixEndpointBuilder(BizPropConstant.CYC_COS_REGION);
clientConfig.setEndpointBuilder(endpointBuilder);
}
// 这里建议设置使用 https 协议
if(HttpProtocol.https.name().equals(BizPropConstant.CYC_HTTP_PROTOCOL)){
clientConfig.setHttpProtocol(HttpProtocol.https);
}else{
clientConfig.setHttpProtocol(HttpProtocol.http);
}
clientConfig.setMaxErrorRetry(3);//重试3次
// clientConfig.
// 3 生成 cos 客户端。
if (cosClientCYC == null) {
synchronized (FileCloudStoreUtils.class) {
if (cosClientCYC == null) {
cosClientCYC = new COSClient(cred, clientConfig);
logger.info("云对象客户端创建......");
}
}
}
return cosClientCYC;
}
return null;
}//使用单例模式中懒汉式
/**
* author huangrq <p>
* description (用一句话描述这个方法)<p>
* date 2022/4/7 17:23<p>
*
* @param bucketName
* @param key
* @param localFilePath
* @return void
**/
public boolean fileCloudUpload(String bucketName, String key, String localFilePath,String systemId,long fileSize) {
long start = System.currentTimeMillis();
logger.info("对象存储开始{},{},{}",bucketName,key,localFilePath);
try (FileInputStream fis = new FileInputStream(localFilePath)) {
ObjectMetadata objectMetadata = new ObjectMetadata();
// 上传的流如果能够获取准确的流长度,则推荐一定填写 content-length
// 如果确实没办法获取到,则下面这行可以省略,但同时高级接口也没办法使用分块上传了
objectMetadata.setContentLength(fileSize);
// 上传逻辑
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, fis,objectMetadata);
PutObjectResult putObjectResult = getCOSClient(systemId).putObject(putObjectRequest);
String eTag = putObjectResult.getETag();
if (StringUtils.isNotBlank(eTag)) {
logger.info("对象存储成功{},{},{} cost {} ms",bucketName,key,localFilePath,(System.currentTimeMillis()-start));
return true;
}
} catch (IOException e) {
logger.error("I/O error:", e);
}catch (CosClientException e) { // 更具体的异常类型
logger.error("对象存储异常:{}", e);
} catch (Exception e) { // 其他类型的异常
String dh = StringUtils.substringBeforeLast(StringUtils.substringAfterLast(localFilePath, File.separator), ".");
logger.error("对象存储异常:{},{},{} dh:{}", bucketName, key, localFilePath, dh, e);
}
return false;
}
public Boolean downloadFileCloud(String bucketName, String key, String localFilePath,String systemId) throws IOException {
long start = System.currentTimeMillis();
try {
logger.info("对象存储下载开始 {},{},{}",bucketName,key,localFilePath);
// Bucket的命名格式为 BucketName-APPID ,此处填写的存储桶名称必须为此格式
// 指定文件在 COS 上的路径,即对象键。例如对象键为folder/picture.jpg,则表示下载的文件 picture.jpg 在 folder 路径下
// 方法1 获取下载输入流
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
//下载文件到本地的路径,例如 D 盘的某个目录
// localFilePath = FileUtil.filePathFilter(localFilePath);
// if(StringUtils.isEmpty(localFilePath)){
// logger.error("FileCloudStoreUtils-->downloadFileCloud请求入参localFilePath不符合规范");
// return false;
// }
File downFile = new File(localFilePath);
ObjectMetadata downObjectMeta = getCOSClient(systemId).getObject(getObjectRequest, downFile);
String eTag = downObjectMeta.getETag();
if(StringUtils.isNotBlank(eTag)){
logger.info("对象存储下载成功 {},{},{} cost {} ms",bucketName,key,localFilePath,(System.currentTimeMillis()-start));
return true;
}
}catch (Exception e) {
logger.info("对象存储下载失败 {},{},{} cost {} ms",bucketName,key,localFilePath,(System.currentTimeMillis()-start),e);
String dh = StringUtils.substringBeforeLast(StringUtils.substringAfterLast(localFilePath,File.separator),".");
logger.error("对象存储异常:{}",bucketName,key,localFilePath,dh,e);
}
return false;
}//上传下载功能记得释放内存,防止内存过高(经过测试不会出现内存溢出情况(OOM),但是在双节点,jdk1.8版本出现内存过高,jvm垃圾回收情况不理想)
public boolean delFileCloud(String bucketName, String key,String systemId) {
// Bucket的命名格式为 BucketName-APPID ,此处填写的存储桶名称必须为此格式
// 指定被删除的文件在 COS 上的路径,即对象键。例如对象键为folder/picture.jpg,则表示删除位于 folder 路径下的文件 picture.jpg
getCOSClient(systemId).deleteObject(bucketName, key);
return true;
}
}
springboot整合腾讯云cos对象存储功能
于 2024-08-02 08:51:05 首次发布