k8s中通过aws sdk访问s3遇到的坑

背景

公司有一套基于k8s的paas系统,现在pod中安装了aws 命令行工具

RUN apk add py-pip && pip install awscli

可以使用命令直接get、put文件,如下:
在这里插入图片描述
由于java使用命令行时可能会出现卡死现象,所以这里想使用aws提供的sdk来直接上传下载文件。
默认有两种方式,一种是程序中配置key:

BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, awsSecretKey);
            s3 = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).withRegion(Regions.DEFAULT_REGION).build();

另外一种如下:

s3 = AmazonS3ClientBuilder.standard().withCredentials(new ProfileCredentialsProvider()).withRegion(Regions.DEFAULT_REGION).build();

报错

报错一:java.lang.IllegalArgumentException: profile file cannot be null

原因:这里是没找到配置文件,~/.aws/credentials
解决方案:
在dorker中需要直接使用下面方式来初始化s3client

AmazonS3 s3Client = new AmazonS3Client();
或者
AmazonS3 s3Client = new AmazonS3Client(DefaultAWSCredentialsProviderChain.getInstance());

最终初始化代码如下:

s3 = AmazonS3ClientBuilder.standard().withCredentials(DefaultAWSCredentialsProviderChain.getInstance()).withRegion(Regions.DEFAULT_REGION).build();

参考链接:
https://stackoverflow.com/questions/41796355/aws-error-downloading-object-from-s3-profile-file-cannot-be-null

报错二:Amazon S3 exception: “The specified key does not exist”

详细报错:

com.amazonaws.services.s3.model.AmazonS3Exception: 
The specified key does not exist.
 (Service: Amazon S3; Status Code: 404; Error Code: NoSuchKey;

代码如下:

 public static void downloadFile(String fileName,String savePath) {
        S3Object s3Object = s3.getObject(bucketName, fileName);
        FileOutputStream fos = null;
        try (S3ObjectInputStream s3input = s3Object.getObjectContent()){
            fos = new FileOutputStream(new File(savePath));
            byte[] read_buf = new byte[1024];
            int read_len = 0;
            while ((read_len = s3input.read(read_buf)) > 0) {
                fos.write(read_buf, 0, read_len);
            }
            s3Object.close();
            fos.close();
        } catch (Exception e) {
            log.warn("获取文件异常:fileName={},savePath={}",fileName,savePath,e);
            throw new AppException("获取文件异常:fileName="+fileName+",savePath="+savePath);
        } finally {
            try{
                if(fos!=null) {
                    fos.close();
                }
            }catch (IOException e){
                log.warn("关闭文件流异常:fileName={},savePath={}",fileName,savePath,e);
            }
        }
    }

原因:这里是只找不到文件
解决方案:检查s3上的文件路径是否正确,
举个例子:s3://bucket_name/aa/bb/mm.csv
这里的fileName参数应该传“aa/bb/mm.csv”;

报错三:/data/xx/xx/aa.csv not exists

这个原因比较明显,是目标文件找不到,请先确认号父目录是否创建

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值