
本文将指导你如何使用 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 对象。
首先,创建一个简单的 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 客户端:
@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 存储桶名称和文件名称。
本文介绍了两种使用 Spring Boot 和 AWS SDK 从 S3 读取 JSON 对象列表的方法。第一种方法将 S3 文件下载到本地文件系统,然后进行处理;第二种方法直接在内存中处理 S3 文件,避免了创建本地文件的步骤。选择哪种方法取决于你的具体需求和文件大小。希望本文能够帮助你更好地理解如何在 Spring Boot 应用中使用 AWS S3。
以上就是使用 Spring Boot 从 AWS S3 读取 JSON 对象列表的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号