私はS3バケットxxxを持っています。 s3バケットからデータにアクセスし、その詳細をRDS PostgreSQLインスタンスに書き込むためのlambda関数を書きました。私は自分のコードでそれをすることができます。ファイルがs3になったときに同じ関数を呼び出すためのラムダ関数に1つのトリガを追加しました。s3バケットから指定されたキーにアクセスしますか?
私のコードからは、名前が 'sampleData.csv'のファイルしか読み取れません。あなたは、私がキー=「SampleData.csv」を言及していることがわかります私のコードから
public class LambdaFunctionHandler implements RequestHandler<S3Event, String> {
private AmazonS3 s3 = AmazonS3ClientBuilder.standard().build();
public LambdaFunctionHandler() {}
// Test purpose only.
LambdaFunctionHandler(AmazonS3 s3) {
this.s3 = s3;
}
@Override
public String handleRequest(S3Event event, Context context) {
context.getLogger().log("Received event: " + event);
String bucket = "xxx";
String key = "SampleData.csv";
System.out.println(key);
try {
S3Object response = s3.getObject(new GetObjectRequest(bucket, key));
String contentType = response.getObjectMetadata().getContentType();
context.getLogger().log("CONTENT TYPE: " + contentType);
// Read the source file as text
AmazonS3 s3Client = new AmazonS3Client();
String body = s3Client.getObjectAsString(bucket, key);
System.out.println("Body: " + body);
System.out.println();
System.out.println("Reading as stream.....");
System.out.println();
BufferedReader br = new BufferedReader(new InputStreamReader(response.getObjectContent()));
// just saving the excel sheet data to the DataBase
String csvOutput;
try {
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://ENDPOINT:5432/DBNAME","USER", "PASSWORD");
System.out.println("Connected");
// Checking EOF
while ((csvOutput = br.readLine()) != null) {
String[] str = csvOutput.split(",");
String name = str[1];
String query = "insert into schema.tablename(name) values('"+name+"')";
Statement statement = con.createStatement();
statement.executeUpdate(query);
}
System.out.println("Inserted Successfully!!!");
}catch (Exception ase) {
context.getLogger().log(String.format(
"Error getting object %s from bucket %s. Make sure they exist and"
+ " your bucket is in the same region as this function.", key, bucket));
// throw ase;
}
return contentType;
} catch (Exception e) {
e.printStackTrace();
context.getLogger().log(String.format(
"Error getting object %s from bucket %s. Make sure they exist and"
+ " your bucket is in the same region as this function.", key, bucket));
throw e;
}
}
の下に与えられた自分のコードを検討します。特定のファイル名を指定せずにキーを取得する方法はありますか?
本当にありがとう...それは私のために働く.2番目のリンク。もう1つ質問があります。 s3バケットから最新のオブジェクトを取得したい。それを得る方法はありますか?実際に私の要件は、ファイルがs3になると、s3から読み込んでRDS postgreSQLインスタンスに保存することです。 smple.csvがs3になると、ラムダ関数が呼び出され、データはdbに保存されます。次の別のファイル 'sample2.csv'はs3上にあり、sample.csvとsample2.csvが必要です。私はちょうど最新のものを読んでみたいです。何か案が? –