
本文档详细介绍了如何在 Spring Boot 应用程序中从 AWS S3 存储桶读取包含 JSON 行的文件,并将这些 JSON 行转换为 Java 对象列表。文章提供了两种不同的实现方法,分别演示了将 S3 文件读取到本地文件系统再进行处理,以及直接在内存中处理 S3 文件内容,并附带了完整的代码示例和配置说明。
在开始之前,请确保你已经具备以下条件:
首先,需要在 pom.xml 文件中添加 AWS S3 SDK 的依赖。
<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>s3</artifactId>
    <version>2.17.285</version>
</dependency>创建一个配置类,用于配置和创建 S3Client 实例。需要提供 AWS 访问密钥 ID 和密钥,以及 S3 区域。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
@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 是否正确。
定义一个 Person 类,用于映射 S3 文件中的 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 + '\'' +
                '}';
    }
}创建一个名为 AwsS3Service 的服务类,用于从 S3 存储桶读取文件,并将其转换为 Person 对象列表。
 
                        Easily find JSON paths within JSON objects using our intuitive Json Path Finder
 30
30
                             
                    import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
@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;
    }
}此版本的服务首先将 S3 文件读取到本地文件系统,然后将其转换为对象列表。
以下是另一种实现方式,它直接在内存中处理 S3 文件内容,避免了创建临时文件。
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
@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;
    }
}创建一个 Spring Boot 应用,并使用 AwsS3Service 来读取 S3 文件并打印结果。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.List;
@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"); // 或者使用 readFileAndCreateObjectList
        System.out.println(peoples);
    }
}请将 BUCKET_NAME 和 KEY_NAME 替换为你的 S3 存储桶名称和文件名称。
运行 Spring Boot 应用程序。控制台应该会打印出从 S3 文件读取的 Person 对象列表。
[Person{name='rohit', surname='sharma'}, Person{name='virat', surname='kohli'}]本文档介绍了如何在 Spring Boot 应用程序中从 AWS S3 存储桶读取 JSON 数据并将其转换为 Java 对象列表。提供了两种不同的实现方法,可以根据实际需求选择合适的方式。 通过使用 AWS S3 SDK 和 Spring Boot,可以方便地从云存储中读取数据,并将其集成到应用程序中。
以上就是Spring Boot: 从 AWS S3 读取 JSON 数据并转换为对象列表的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号