properties配置类
TencentCos.APPID=xxxxx
TencentCos.SecretId=xxxxxxx
TencentCos.SecretKey=xxxxxx
TencentCos.testBucket=xxxxxx
TencentCos.CosPath=https://xxxxxxxx.cos.ap-chengdu.myqcloud.com
TencentCos.region=ap-chengdu
读取properties中的配置
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/*** 读取yml中的配置*/
@Component
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TencentConfig implements InitializingBean {@Value("${TencentCos.CosPath}")private String cosPath;@Value("${TencentCos.SecretId}")private String secretId;@Value("${TencentCos.SecretKey}")private String secretKey;@Value("${TencentCos.region}")private String regionName;@Value("${TencentCos.testBucket}")private String bucketName;@Value("${TencentCos.APPID}")private String appId ;public static String COSPATH;public static String SECRET_ID;public static String SECRET_KEY;public static String REGION_NAME;public static String BUCKET_NAME;public static String APPID;@Overridepublic void afterPropertiesSet() throws Exception {COSPATH = cosPath;SECRET_ID = secretId;SECRET_KEY = secretKey;REGION_NAME = regionName;BUCKET_NAME = bucketName;APPID = appId;}
}
初始化cos客户端
//初始化cos客户端public COSClient cosClientnew(String secretId, String secretKey, String regionName){// 1 初始化用户身份信息(secretId, secretKey)。// SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);// 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。Region region = new Region(regionName);ClientConfig clientConfig = new ClientConfig(region);// 这里建议设置使用 https 协议// 从 5.6.54 版本开始,默认使用了 httpsclientConfig.setHttpProtocol(HttpProtocol.https);// 以下的设置,是可选的:// 设置 socket 读取超时,默认 30sclientConfig.setSocketTimeout(30*1000);// 设置建立连接超时,默认 30sclientConfig.setConnectionTimeout(30*1000);// 3 初始化 cos 客户端。return new COSClient(cred, clientConfig);}
测试读取数据
@Testpublic void test01wwww1(){COSClient cosClient = cosClientnew(TencentConfig.SECRET_ID,TencentConfig.SECRET_KEY,TencentConfig.REGION_NAME);// Bucket 的命名格式为 BucketName-APPID ,此处填写的存储桶名称必须为此格式String bucketName = "donglin-1304838938";String key = "ldl.txt";try {ObjectMetadata objectMetadata = cosClient.getObjectMetadata(bucketName, key);System.out.println(objectMetadata.getContentLength());} catch (CosServiceException e) {e.printStackTrace();} catch (CosClientException e) {e.printStackTrace();}}
测试