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

這個原因比較明顯,是目標文件找不到,請先確認號父目錄是否創建

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章