Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring batch file writer to write directly to amazon s3 storage without PutObjectRequest

I'm trying to upload a file to amazon s3. Instead of uploading, I want to read the data from database using spring batch and write the file directly into the s3 storage. Is there anyway we can do that ?

like image 618
user3540722 Avatar asked Jun 04 '18 17:06

user3540722


1 Answers

Spring Cloud AWS adds support for the Amazon S3 service to load and write resources with the resource loader and the s3 protocol. Once you have configured the AWS resource loader, you can write a custom Spring Batch writer like:

import java.io.OutputStream;
import java.util.List;

import org.springframework.batch.item.ItemWriter;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.WritableResource;

public class AwsS3ItemWriter implements ItemWriter<String> {

    private ResourceLoader resourceLoader;

    private WritableResource resource;

    public AwsS3ItemWriter(ResourceLoader resourceLoader, String resource) {
        this.resourceLoader = resourceLoader;
        this.resource = (WritableResource) this.resourceLoader.getResource(resource);
    }

    @Override
    public void write(List<? extends String> items) throws Exception {
        try (OutputStream outputStream = resource.getOutputStream()) {
            for (String item : items) {
                outputStream.write(item.getBytes());
            }
        }
    }
}

Then you should be able to use this writer with an S3 resource like s3://myBucket/myFile.log.

Is there anyway we can do that ?

Please note that I did not compile/test the previous code. I just wanted to give you a starting point of how to do it.

Hope this helps.

like image 188
Mahmoud Ben Hassine Avatar answered Sep 28 '22 00:09

Mahmoud Ben Hassine