使用 Spring Boot 从 AWS S3 读取 JSON 对象列表(读取.对象.列表.Boot.Spring...)

wufei123 发布于 2025-08-29 阅读(5)

使用 spring boot 从 aws s3 读取 json 对象列表

本文将指导你如何使用 Spring Boot 和 AWS SDK 从 S3 存储桶中读取包含多个 JSON 行的文件,并将这些行转换为 Java 对象列表。我们将会探讨两种不同的实现方式:一种是将 S3 文件读取到本地文件系统,然后进行处理;另一种是直接在内存中处理 S3 文件。

准备工作

首先,确保你已经配置好了 AWS 凭证,并且拥有访问 S3 存储桶的权限。你还需要在 pom.xml 文件中添加 AWS SDK 的依赖:

<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>s3</artifactId>
    <version>2.17.285</version>
</dependency>

假设你的 S3 存储桶中有一个名为 filename.txt 的文件,内容如下:

{
   "name":"rohit",
   "surname":"sharma"
}
{
   "name":"virat",
   "surname":"kohli"
}

我们希望将每一行 JSON 数据解析为 Person 对象。

创建 Person 类

首先,创建一个简单的 Java 类 Person,用于存储 JSON 数据:

public class Person {
    private String name;
    private String surname;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", surname='" + surname + '\'' +
                '}';
    }
}
配置 AWS S3 客户端

创建一个配置类,用于初始化 AWS S3 客户端:

@Configuration
public class AwsS3ClientConfig {

    @Bean
    public S3Client s3Client(){
        AwsBasicCredentials awsBasicCredentials = AwsBasicCredentials.create("ACCESS_KEY_ID", "SECRET_ACCESS_KEY");
        return S3Client
                .builder()
                .region(Region.US_EAST_1)
                .credentialsProvider(StaticCredentialsProvider.create(awsBasicCredentials))
                .build();
    }
}

请务必替换 "ACCESS_KEY_ID" 和 "SECRET_ACCESS_KEY" 为你实际的 AWS 凭证。 Region.US_EAST_1 也要替换成你S3桶所在的区域。

实现方式一:读取到本地文件系统

这种方式首先将 S3 文件下载到本地文件系统,然后读取文件内容并解析为 Person 对象列表。

@Service
public class AwsS3Service {

    private final S3Client s3Client;

    @Autowired
    public AwsS3Service(S3Client s3Client) {
        this.s3Client = s3Client;
    }


    public List<Person> readFileAndCreateList(String bucketName, String keyName) throws IOException {
        final Path file = readFile(bucketName, keyName);
        return convertFileToList(file);
    }

    private Path readFile(String bucketName, String keyName) throws IOException {
        GetObjectRequest getObjectRequest = GetObjectRequest
                .builder()
                .bucket(bucketName)
                .key(keyName)
                .build();

        final byte[] bytes = s3Client
                .getObject(getObjectRequest)
                .readAllBytes();
        final Path path = Paths.get("demo.txt");
        Files.write(path, bytes);
        return path;
    }

    private List<Person> convertFileToList(Path path) throws IOException {
        final List<String> lines = Files.readAllLines(path);
        StringBuilder json = new StringBuilder();
        List<Person> persons=new ArrayList<>();
        for (String line : lines) {
            if ("{".equals(line)) {
                json = new StringBuilder("{");
            } else if ("}".equals(line)) {
                json.append("}");
               persons.add(new ObjectMapper()
                        .readValue(json.toString(), Person.class));
            } else {
                json.append(line.trim());
            }
        }
        return persons;
    }
}

这段代码首先通过 readFile 方法从 S3 下载文件,然后使用 convertFileToList 方法读取文件内容,逐行解析 JSON 数据,并将其转换为 Person 对象。

实现方式二:在内存中处理

这种方式直接从 S3 读取文件内容到内存,避免了创建本地文件的步骤。

@Service
public class AwsS3Service {

    private final S3Client s3Client;

    @Autowired
    public AwsS3Service(S3Client s3Client) {
        this.s3Client = s3Client;
    }


    public List<Person> readFileAndCreateObjectList(String bucketName, String keyName) throws IOException {
        final List<String> lines = readFile(bucketName, keyName);
        return convertFileLinesToObjectList(lines);
    }

    private List<String> readFile(String bucketName, String keyName) throws IOException {
        GetObjectRequest getObjectRequest = GetObjectRequest
                .builder()
                .bucket(bucketName)
                .key(keyName)
                .build();

        byte[] bytes;
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            s3Client
                    .getObject(getObjectRequest)
                    .transferTo(byteArrayOutputStream);
            bytes = byteArrayOutputStream.toByteArray();
        }

        List<String> lines=new ArrayList<>();
        try(ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            InputStreamReader inputStreamReader = new InputStreamReader(byteArrayInputStream);
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader)){
           while (bufferedReader.ready()){
              lines.add(bufferedReader.readLine());
           }
        }
        return lines;
    }

    private List<Person> convertFileLinesToObjectList(List<String> lines) throws IOException {
        StringBuilder json = new StringBuilder();
        List<Person> persons = new ArrayList<>();
        for (String line : lines) {
            if ("{".equals(line)) {
                json = new StringBuilder("{");
            } else if ("}".equals(line)) {
                json.append("}");
                persons.add(new ObjectMapper()
                        .readValue(json.toString(), Person.class));
            } else {
                json.append(line.trim());
            }
        }
        return persons;
    }
}

这段代码使用 ByteArrayOutputStream 和 ByteArrayInputStream 将 S3 文件内容读取到内存中,然后使用 BufferedReader 逐行读取并解析 JSON 数据。

使用示例

创建一个 Spring Boot 应用,并在 CommandLineRunner 中调用上述服务:

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    private final AwsS3Service awsS3Service;

    @Autowired
    public DemoApplication(AwsS3Service awsS3Service) {
        this.awsS3Service = awsS3Service;
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class);
    }

    @Override
    public void run(String... args) throws Exception {
        //KEY_NAME==filename.txt
        final List<Person> peoples =
                awsS3Service
                        .readFileAndCreateList("BUCKET_NAME", "KEY_NAME");
        System.out.println(peoples);
    }
}

请将 "BUCKET_NAME" 和 "KEY_NAME" 替换为你实际的 S3 存储桶名称和文件名称。

注意事项
  • 异常处理: 在实际应用中,需要添加更完善的异常处理机制,例如处理 S3 连接错误、文件不存在等情况。
  • 性能优化: 如果文件非常大,可以考虑使用 S3 Select API 进行过滤,或者使用分页读取的方式来减少内存占用。
  • JSON 解析: 使用 ObjectMapper 解析 JSON 数据时,需要确保 JSON 格式正确,否则会抛出异常。
  • 资源释放: 在处理 I/O 流时,务必使用 try-with-resources 语句确保资源被正确释放。
总结

本文介绍了两种使用 Spring Boot 和 AWS SDK 从 S3 读取 JSON 对象列表的方法。第一种方法将 S3 文件下载到本地文件系统,然后进行处理;第二种方法直接在内存中处理 S3 文件,避免了创建本地文件的步骤。选择哪种方法取决于你的具体需求和文件大小。希望本文能够帮助你更好地理解如何在 Spring Boot 应用中使用 AWS S3。

以上就是使用 Spring Boot 从 AWS S3 读取 JSON 对象列表的详细内容,更多请关注知识资源分享宝库其它相关文章!

标签:  读取 对象 列表 

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。