这里使用新版的SDK2进行开发:
    pom依赖:

    1. <dependency>
    2. <groupId>software.amazon.awssdk</groupId>
    3. <artifactId>s3</artifactId>
    4. <version>2.17.64</version>
    5. </dependency>

    官方SDK文档:https://docs.aws.amazon.com/zh_cn/sdk-for-java/latest/developer-guide/home.html

    S3Config封装

    1. public class S3Config {
    2. private String accessKeyId;
    3. private String secretAccessKey;
    4. private String region;
    5. private String defaultBucket;
    6. public S3Config() {
    7. }
    8. public S3Config(String accessKeyId, String secretAccessKey, String region, String defaultBucket) {
    9. this.accessKeyId = accessKeyId;
    10. this.secretAccessKey = secretAccessKey;
    11. this.region = region;
    12. this.defaultBucket = defaultBucket;
    13. }
    14. public String getAccessKeyId() {
    15. return accessKeyId;
    16. }
    17. public void setAccessKeyId(String accessKeyId) {
    18. this.accessKeyId = accessKeyId;
    19. }
    20. public String getSecretAccessKey() {
    21. return secretAccessKey;
    22. }
    23. public void setSecretAccessKey(String secretAccessKey) {
    24. this.secretAccessKey = secretAccessKey;
    25. }
    26. public String getRegion() {
    27. return region;
    28. }
    29. public void setRegion(String region) {
    30. this.region = region;
    31. }
    32. public String getDefaultBucket() {
    33. return defaultBucket;
    34. }
    35. public void setDefaultBucket(String defaultBucket) {
    36. this.defaultBucket = defaultBucket;
    37. }
    38. }

    Util封装:

    1. /**
    2. * AWS S3(simple storage service)工具类
    3. *
    4. * @author mori
    5. * @date 2021/10/21
    6. */
    7. public class AmazonS3Util {
    8. private static final Logger log = LoggerFactory.getLogger(AmazonS3Util.class);
    9. private static S3Client s3Client;
    10. private static S3Config s3Config;
    11. /**
    12. * 初始化s3 client
    13. *
    14. * @param config config
    15. */
    16. private static void init(S3Config config) {
    17. try {
    18. log.info("AWS S3 S3Client init...");
    19. s3Config = config;
    20. AwsBasicCredentials awsBasicCredentials = AwsBasicCredentials.create(
    21. config.getAccessKeyId(), config.getSecretAccessKey());
    22. s3Client = S3Client.builder()
    23. .region(Region.of(config.getRegion()))
    24. .credentialsProvider(StaticCredentialsProvider.create(awsBasicCredentials))
    25. .build();
    26. List<Bucket> buckets = listBucket();
    27. String defaultBucket = s3Config.getDefaultBucket();
    28. if (CollectionUtils.isNotEmpty(buckets)) {
    29. Bucket bucket = buckets.stream()
    30. .filter(b -> Objects.equals(defaultBucket, b.name())).findFirst().orElse(null);
    31. if (Objects.nonNull(bucket)) {
    32. log.info("default bucket '{}' already exists.", defaultBucket);
    33. return;
    34. }
    35. }
    36. log.info("default bucket '{}' does not exist, start to create...", defaultBucket);
    37. boolean res = createBucket(defaultBucket);
    38. if (!res) {
    39. throw new RuntimeException("create default bucket failed.");
    40. }
    41. } catch (Exception e) {
    42. log.error("AWS S3Client init failed, error message: {}", e.getMessage());
    43. throw new RuntimeException("AWS S3Client init failed,", e);
    44. }
    45. }
    46. /**
    47. * 构建存储对象请求
    48. *
    49. * @param bucket 对象桶
    50. * @param key 对象key
    51. * @return {@link PutObjectRequest}
    52. */
    53. private static PutObjectRequest createPutObjectRequest(String bucket, String key) {
    54. return PutObjectRequest.builder()
    55. .bucket(bucket)
    56. .key(key)
    57. .build();
    58. }
    59. /**
    60. * 存储对象到默认设置的桶中
    61. *
    62. * @param key 对象key
    63. * @param requestBody 需要存储的对象
    64. * @return boolean
    65. */
    66. public static boolean putObject(String key, RequestBody requestBody) {
    67. return putObject(s3Config.getDefaultBucket(), key, requestBody);
    68. }
    69. /**
    70. * 存储对象到默认设置的桶中
    71. *
    72. * @param key 对象key
    73. * @param path 路径
    74. * @return boolean
    75. */
    76. public static boolean putObject(String key, Path path) {
    77. return putObject(s3Config.getDefaultBucket(), key, path);
    78. }
    79. /**
    80. * 获取对象输入流, 默认桶
    81. *
    82. * @param key 对象key
    83. * @return {@link GetObjectResponse}
    84. */
    85. public static ResponseInputStream<GetObjectResponse> getObject(String key) {
    86. return getObject(s3Config.getDefaultBucket(), key);
    87. }
    88. /**
    89. * 获取对象字节数组, 默认桶
    90. *
    91. * @param key 对象key
    92. * @return {@link GetObjectResponse}
    93. */
    94. public static ResponseBytes<GetObjectResponse> getObjectAsBytes(String key) {
    95. return getObjectAsBytes(s3Config.getDefaultBucket(), key);
    96. }
    97. /**
    98. * 删除对象, 默认桶
    99. *
    100. * @param key 对象key
    101. * @return boolean
    102. */
    103. public static boolean deleteObject(String key) {
    104. return deleteObject(s3Config.getDefaultBucket(), key);
    105. }
    106. /**
    107. * 删除桶中的对象列表,默认桶
    108. *
    109. * @param objectNames 对象名称列表
    110. * @return true表示删除成功
    111. */
    112. public static boolean deleteObjects(List<String> objectNames) {
    113. return deleteObjects(s3Config.getDefaultBucket(), objectNames);
    114. }
    115. /**
    116. * 当前桶对象列表
    117. *
    118. * @return 对象列表 {@link S3Object}>
    119. */
    120. public static List<S3Object> listCurrentBucketObjects() {
    121. return listBucketObjects(s3Config.getDefaultBucket());
    122. }
    123. /**
    124. * 创建存储桶
    125. *
    126. * @param bucketName 存储桶名称
    127. * @return true表示创建成功
    128. */
    129. public static boolean createBucket(String bucketName) {
    130. try {
    131. log.info("AWS S3 create bucket..., bucketName: '{}'", bucketName);
    132. S3Waiter s3Waiter = s3Client.waiter();
    133. CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
    134. .bucket(bucketName)
    135. .build();
    136. s3Client.createBucket(bucketRequest);
    137. HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder()
    138. .bucket(bucketName)
    139. .build();
    140. WaiterResponse<HeadBucketResponse> waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait);
    141. waiterResponse.matched().response().ifPresent(res -> log.info(res.toString()));
    142. log.info("AWS S3 bucket {} is ready", bucketName);
    143. return true;
    144. } catch (S3Exception e) {
    145. log.error("AWS S3 create bucket failed, bucketName: {}, error detail message: {}",
    146. bucketName, e.awsErrorDetails().errorMessage());
    147. return false;
    148. }
    149. }
    150. /**
    151. * 列出所有存储桶
    152. *
    153. * @return 存储桶列表,通过name函数可以获得桶名称
    154. */
    155. public static List<Bucket> listBucket() {
    156. try {
    157. ListBucketsRequest listBucketsRequest = ListBucketsRequest.builder().build();
    158. ListBucketsResponse listBucketsResponse = s3Client.listBuckets(listBucketsRequest);
    159. return listBucketsResponse.buckets();
    160. } catch (S3Exception e) {
    161. log.error("AWS S3 list bucket failed, error detail message: {}", e.awsErrorDetails().errorMessage());
    162. return null;
    163. }
    164. }
    165. /**
    166. * 删除存储桶
    167. *
    168. * @param bucketName 存储桶名称
    169. * @return true表示删除成功
    170. */
    171. public static boolean deleteBucket(String bucketName) {
    172. try {
    173. log.info("AWS S3 delete bucket..., bucketName: '{}'", bucketName);
    174. DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder().bucket(bucketName).build();
    175. s3Client.deleteBucket(deleteBucketRequest);
    176. log.info("AWS S3 delete bucket complete, bucketName: '{}'", bucketName);
    177. return true;
    178. } catch (S3Exception e) {
    179. log.error("AWS S3 deleted bucket failed, error detail message: {}", e.awsErrorDetails().errorMessage());
    180. return false;
    181. }
    182. }
    183. /**
    184. * 删除桶中的对象列表
    185. *
    186. * @param bucketName 存储桶名称
    187. * @param objectNames 对象名称列表
    188. * @return true表示删除成功
    189. */
    190. public static boolean deleteObjects(String bucketName, List<String> objectNames) {
    191. try {
    192. String objects = Arrays.toString(objectNames.toArray());
    193. log.info("AWS S3 delete multiple objects..., bucketName: '{}', keys: '{}'",
    194. bucketName, objects);
    195. ArrayList<ObjectIdentifier> keys = new ArrayList<>();
    196. for (String objectName : objectNames) {
    197. keys.add(ObjectIdentifier.builder().key(objectName).build());
    198. }
    199. DeleteObjectsRequest multiObjectDeleteRequest = DeleteObjectsRequest.builder()
    200. .bucket(bucketName)
    201. .delete(Delete.builder().objects(keys).build())
    202. .build();
    203. s3Client.deleteObjects(multiObjectDeleteRequest);
    204. log.info("AWS S3 delete multiple objects complete, bucketName: '{}', keys: '{}'", bucketName, objects);
    205. return true;
    206. } catch (S3Exception e) {
    207. log.error("AWS S3 deleted multiple objects failed, error detail message: {}", e.awsErrorDetails().errorMessage());
    208. return false;
    209. }
    210. }
    211. /**
    212. * 存储对象
    213. *
    214. * @param bucketName bucket名称
    215. * @param key 对象key
    216. * @param requestBody 需要存储的对象
    217. * @return boolean
    218. */
    219. public static boolean putObject(String bucketName, String key, RequestBody requestBody) {
    220. try {
    221. log.info("AWS S3 uploading object..., bucketName: '{}', key: '{}'", bucketName, key);
    222. PutObjectRequest putObjectRequest = createPutObjectRequest(bucketName, key);
    223. s3Client.putObject(putObjectRequest, requestBody);
    224. log.info("AWS S3 upload object complete, bucketName: '{}', key: '{}'", bucketName, key);
    225. return true;
    226. } catch (S3Exception e) {
    227. log.error("AWS S3 put object failed, error detail message: {}", e.awsErrorDetails().errorMessage());
    228. return false;
    229. }
    230. }
    231. /**
    232. * 存储对象
    233. *
    234. * @param bucketName bucket名称
    235. * @param key 对象key
    236. * @param path 路径
    237. * @return boolean
    238. */
    239. public static boolean putObject(String bucketName, String key, Path path) {
    240. try {
    241. log.info("AWS S3 uploading object..., bucketName: '{}', key: '{}'", bucketName, key);
    242. PutObjectRequest putObjectRequest = createPutObjectRequest(bucketName, key);
    243. s3Client.putObject(putObjectRequest, path);
    244. log.info("AWS S3 upload object complete, bucketName: '{}', key: '{}'", bucketName, key);
    245. return true;
    246. } catch (S3Exception e) {
    247. log.error("AWS S3 put object failed, error detail message: {}", e.awsErrorDetails().errorMessage());
    248. return false;
    249. }
    250. }
    251. /**
    252. * 获取对象输入流
    253. *
    254. * @param bucketName bucket名称
    255. * @param key 对象key
    256. * @return {@link GetObjectResponse}
    257. */
    258. public static ResponseInputStream<GetObjectResponse> getObject(String bucketName, String key) {
    259. try {
    260. GetObjectRequest getObjectRequest = GetObjectRequest.builder()
    261. .bucket(bucketName)
    262. .key(key)
    263. .build();
    264. return s3Client.getObject(getObjectRequest);
    265. } catch (S3Exception e) {
    266. log.error("AWS S3 get object failed, error detail message: {}", e.awsErrorDetails().errorMessage());
    267. return null;
    268. }
    269. }
    270. /**
    271. * 获取对象字节数组
    272. *
    273. * @param bucketName bucket名称
    274. * @param key 对象key
    275. * @return {@link GetObjectResponse}
    276. */
    277. public static ResponseBytes<GetObjectResponse> getObjectAsBytes(String bucketName, String key) {
    278. try {
    279. GetObjectRequest getObjectRequest = GetObjectRequest.builder()
    280. .bucket(bucketName)
    281. .key(key)
    282. .build();
    283. return s3Client.getObjectAsBytes(getObjectRequest);
    284. } catch (S3Exception e) {
    285. log.error("AWS S3 get object failed, error detail message: {}", e.awsErrorDetails().errorMessage());
    286. return null;
    287. }
    288. }
    289. /**
    290. * 删除对象
    291. *
    292. * @param bucketName bucket名称
    293. * @param key 对象key
    294. * @return boolean
    295. */
    296. public static boolean deleteObject(String bucketName, String key) {
    297. try {
    298. log.info("AWS S3 delete object..., bucketName: '{}', key: '{}'", bucketName, key);
    299. DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()
    300. .bucket(bucketName)
    301. .key(key)
    302. .build();
    303. s3Client.deleteObject(deleteObjectRequest);
    304. log.info("AWS S3 delete object complete, bucketName: '{}', key: '{}'", bucketName, key);
    305. return true;
    306. } catch (S3Exception e) {
    307. log.error("AWS S3 delete object failed, error detail message: {}", e.awsErrorDetails().errorMessage());
    308. return false;
    309. }
    310. }
    311. /**
    312. * 复制桶中的对象到另一个桶
    313. *
    314. * @param fromBucket 对象存放的原始桶,一个 URL 编码的字符串值(请参阅 URlenCoder.code 方法)
    315. * @param objectKey 对象的key
    316. * @param toBucket 另一个桶
    317. * @return 复制结果
    318. */
    319. public static String copyBucketObject(String fromBucket, String objectKey, String toBucket) {
    320. try {
    321. log.info("AWS S3 copy object..., fromBucket: '{}', objectKey: '{}', toBucket: '{}'",
    322. fromBucket, objectKey, toBucket);
    323. CopyObjectRequest copyObjectRequest = CopyObjectRequest.builder()
    324. .sourceBucket(fromBucket)
    325. .sourceKey(objectKey)
    326. .destinationBucket(toBucket)
    327. .destinationKey(objectKey)
    328. .build();
    329. CopyObjectResponse res = s3Client.copyObject(copyObjectRequest);
    330. log.info("AWS S3 copy object complete, fromBucket: '{}', objectKey: '{}', toBucket: '{}'",
    331. fromBucket, objectKey, toBucket);
    332. return res.copyObjectResult().toString();
    333. } catch (S3Exception e) {
    334. log.error("AWS S3 copy bucket object failed, error detail message: {}", e.awsErrorDetails().errorMessage());
    335. return "";
    336. }
    337. }
    338. /**
    339. * 列出桶中的对象
    340. *
    341. * @param bucketName 桶名称
    342. * @return {@link List}<{@link S3Object}>
    343. */
    344. public static List<S3Object> listBucketObjects(String bucketName) {
    345. try {
    346. ListObjectsRequest listObjectsRequest = ListObjectsRequest
    347. .builder()
    348. .bucket(bucketName)
    349. .build();
    350. ListObjectsResponse res = s3Client.listObjects(listObjectsRequest);
    351. return res.contents();
    352. } catch (S3Exception e) {
    353. log.error("AWS S3 list bucket objects failed, error detail message: {}", e.awsErrorDetails().errorMessage());
    354. return null;
    355. }
    356. }
    357. }

    configuration:

    1. @Configuration
    2. public class AmazonS3Config {
    3. @Value("${amazon.s3.accessKeyId}")
    4. private String accessKeyId;
    5. @Value("${amazon.s3.secretAccessKey}")
    6. private String secretAccessKey;
    7. @Value("${amazon.s3.region}")
    8. private String region;
    9. @Value("${amazon.s3.defaultBucket}")
    10. private String defaultBucket;
    11. @Bean
    12. public S3Config s3Config() {
    13. return new S3Config(accessKeyId, secretAccessKey, region, defaultBucket);
    14. }
    15. @Bean
    16. public MethodInvokingFactoryBean s3ClientInit(S3Config config) {
    17. MethodInvokingFactoryBean invokingFactoryBean = new MethodInvokingFactoryBean();
    18. invokingFactoryBean.setTargetClass(AmazonS3Util.class);
    19. invokingFactoryBean.setTargetMethod("init");
    20. invokingFactoryBean.setArguments(config);
    21. return invokingFactoryBean;
    22. }
    23. }