
本文将指导您如何使用它 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桶所在的区域代替。
实现方法1:读取本地文件系统首先要这样做 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 详情请关注图灵教育的其他相关文章!