背景

公司有一套基于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

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

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐