package com.example.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.services.S3Service;
@RestController
@RequestMapping("/file")
public class S3Controller {
@Autowired
private S3Service s3Service;
@GetMapping("/listAllObjects")
public ResponseEntity<List<String>> viewObjects() {
return new ResponseEntity<>(s3Service.listObjects(),HttpStatus.OK);
}
}
S3控制器
package com.example.demo.entities;
import org.springframework.beans.factory.annotation.Value;
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 S3Config {
@Value("${region}")
private String region;
@Value("${accesskey}")
private String accessKey;
@Value("${secretKey}")
private String secretKey;
@Bean
public S3Client s3Client() {
AwsBasicCredentials credentials = AwsBasicCredentials.create(accessKey, secretKey);
return S3Client.builder()
.credentialsProvider(StaticCredentialsProvider.create(credentials))
.region(Region.of(region))
.build();
}
}
S3配置
package com.example.demo.services;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
import software.amazon.awssdk.services.s3.model.S3Object;
@Service
public class S3Service {
private final S3Client s3Client;
private final String bucketName;
public S3Service(S3Client s3Client, @Value("${bucketName}") String bucketName) {
this.s3Client = s3Client;
this.bucketName = bucketName;
}
public List<String> listObjects() {
ListObjectsResponse response = s3Client.listObjects(builder -> builder.bucket(bucketName));
return response.contents().stream().map(S3Object::key).collect(Collectors.toList());
}
}
S3服务
spring.application.name=webflux-demo
aws.region=${region}
aws.accessKey=${accessKey}
aws.secretKey=${secretKey}
aws.bucketName=${bucketName}
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
应用程序.属性
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
<version>2.25.52</version>
</dependency>