您现在的位置是:首页 >技术交流 >若依框架—基于AmazonS3实现OSS对象存储服务网站首页技术交流
若依框架—基于AmazonS3实现OSS对象存储服务
简介若依框架—基于AmazonS3实现OSS对象存储服务
若依框架—基于AmazonS3实现OSS对象存储,其他也适用
文章目录
- 若依框架—基于AmazonS3实现OSS对象存储,其他也适用
上一篇若依mybatis升级mybatis-plus,其他也适用
自己新建的公共包,你们就放自己想放的位置吧,代码基于若依框架实现
1. 在pom文添中加依赖
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.543</version>
</dependency>
2. 创建OssProperties, 上图是两种写法,举例用的OssProperties2
package com.w.yizhi.common.oss.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* oss
*
* @author yizhi
*/
@Data
@Component
@ConfigurationProperties(prefix = "oss")
public class OssProperties2 {
/**
* 对象存储服务的URL
*/
private String endpoint;
/**
* 区域
*/
private String region;
/**
* true path-style nginx 反向代理和S3默认支持 pathStyle模式 {http://endpoint/bucketname}
* false supports virtual-hosted-style 阿里云等需要配置为 virtual-hosted-style 模式{http://bucketname.endpoint}
* 只是url的显示不一样
*/
private Boolean pathStyleAccess = true;
/**
* Access key
*/
private String accessKey;
/**
* Secret key
*/
private String secretKey;
/**
* 最大线程数,默认:100
*/
private Integer maxConnections = 100;
}
3. 创建OssAutoConfiguration
package com.w.yizhi.common.oss;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.w.yizhi.common.oss.properties.OssProperties2;
import com.w.yizhi.common.oss.service.OssTemplate;
import com.w.yizhi.common.oss.service.impl.OssTemplateImpl;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
;
/**
* aws 自动配置类
*
* @author yizhi
*/
@AllArgsConstructor
@EnableConfigurationProperties({ OssProperties2.class })
public class OssAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public AmazonS3 ossClient(OssProperties2 ossProperties) {
// 客户端配置,主要是全局的配置信息
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setMaxConnections(ossProperties.getMaxConnections());
// url以及region配置
AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(
ossProperties.getEndpoint(), ossProperties.getRegion());
// 凭证配置
AWSCredentials awsCredentials = new BasicAWSCredentials(ossProperties.getAccessKey(),
ossProperties.getSecretKey());
AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
// build amazonS3Client客户端
return AmazonS3Client.builder().withEndpointConfiguration(endpointConfiguration)
.withClientConfiguration(clientConfiguration).withCredentials(awsCredentialsProvider)
.disableChunkedEncoding().withPathStyleAccessEnabled(ossProperties.getPathStyleAccess()).build();
}
@Bean
@ConditionalOnBean(AmazonS3.class)
public OssTemplate ossTemplate(AmazonS3 amazonS3){
return new OssTemplateImpl(amazonS3);
}
}
4. 创建OssTemplateService,添加基本操作
package com.w.yizhi.common.oss.service;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import java.io.InputStream;
import java.util.List;
/**
*
* @author yizhi
*/
public interface OssTemplate {
/**
* 创建bucket
* @param bucketName bucket名称
*/
void createBucket(String bucketName);
/**
* 获取所有的bucket
* @return
*/
List<Bucket> getAllBuckets();
/**
* 通过bucket名称删除bucket
* @param bucketName
*/
void removeBucket(String bucketName);
/**
* 上传文件
* @param bucketName bucket名称
* @param objectName 文件名称
* @param stream 文件流
* @param contextType 文件类型
* @throws Exception
*/
void putObject(String bucketName, String objectName, InputStream stream, String contextType) throws Exception;
/**
* 上传文件
* @param bucketName bucket名称
* @param objectName 文件名称
* @param stream 文件流
* @throws Exception
*/
void putObject(String bucketName, String objectName, InputStream stream) throws Exception;
/**
* 获取文件
* @param bucketName bucket名称
* @param objectName 文件名称
* @return S3Object
*/
S3Object getObject(String bucketName, String objectName);
/**
* 获取对象的url
* @param bucketName
* @param objectName
* @param expires
* @return
*/
String getObjectURL(String bucketName, String objectName, Integer expires);
/**
* 通过bucketName和objectName删除对象
* @param bucketName
* @param objectName
* @throws Exception
*/
void removeObject(String bucketName, String objectName) throws Exception;
/**
* 根据文件前置查询文件
* @param bucketName bucket名称
* @param prefix 前缀
* @param recursive 是否递归查询
* @return S3ObjectSummary 列表
*/
List<S3ObjectSummary> getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive);
}
5. 创建OssTemplateImpl,添加基本操作
package com.w.yizhi.common.oss.service.impl;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import com.amazonaws.util.IOUtils;
import com.w.yizhi.common.oss.service.OssTemplate;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
/**
*
* @author yizhi
*/
@RequiredArgsConstructor
public class OssTemplateImpl implements OssTemplate {
private final AmazonS3 amazonS3;
/**
* 创建Bucket
* AmazonS3:https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html
* @param bucketName bucket名称
*/
@Override
@SneakyThrows
public void createBucket(String bucketName) {
if (!amazonS3.doesBucketExistV2(bucketName) ) {
amazonS3.createBucket((bucketName));
}
}
/**
* 获取所有的buckets
* AmazonS3:https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBuckets.html
* @return
*/
@Override
@SneakyThrows
public List<Bucket> getAllBuckets() {
return amazonS3.listBuckets();
}
/**
* 通过Bucket名称删除Bucket
* AmazonS3:https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucket.html
* @param bucketName
*/
@Override
@SneakyThrows
public void removeBucket(String bucketName) {
amazonS3.deleteBucket(bucketName);
}
/**
* 上传对象
* @param bucketName bucket名称
* @param objectName 文件名称
* @param stream 文件流
* @param contextType 文件类型
* AmazonS3:https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html
*/
@Override
@SneakyThrows
public void putObject(String bucketName, String objectName, InputStream stream, String contextType) {
putObject(bucketName, objectName, stream, stream.available(), contextType);
}
/**
* 上传对象
* @param bucketName bucket名称
* @param objectName 文件名称
* @param stream 文件流
* AmazonS3:https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html
*/
@Override
@SneakyThrows
public void putObject(String bucketName, String objectName, InputStream stream) {
putObject(bucketName, objectName, stream, stream.available(), "application/octet-stream");
}
/**
* 通过bucketName和objectName获取对象
* @param bucketName bucket名称
* @param objectName 文件名称
* @return
* AmazonS3:https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html
*/
@Override
@SneakyThrows
public S3Object getObject(String bucketName, String objectName) {
return amazonS3.getObject(bucketName, objectName);
}
/**
* 获取对象的url
* @param bucketName
* @param objectName
* @param expires
* @return
* AmazonS3:https://docs.aws.amazon.com/AmazonS3/latest/API/API_GeneratePresignedUrl.html
*/
@Override
@SneakyThrows
public String getObjectURL(String bucketName, String objectName, Integer expires) {
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, expires);
URL url = amazonS3.generatePresignedUrl(bucketName, objectName, calendar.getTime());
return url.toString();
}
/**
* 通过bucketName和objectName删除对象
* @param bucketName
* @param objectName
* AmazonS3:https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html
*/
@Override
@SneakyThrows
public void removeObject(String bucketName, String objectName) {
amazonS3.deleteObject(bucketName, objectName);
}
/**
* 根据bucketName和prefix获取对象集合
* @param bucketName bucket名称
* @param prefix 前缀
* @param recursive 是否递归查询
* @return
* AmazonS3:https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjects.html
*/
@Override
@SneakyThrows
public List<S3ObjectSummary> getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive) {
ObjectListing objectListing = amazonS3.listObjects(bucketName, prefix);
return objectListing.getObjectSummaries();
}
/**
*
* @param bucketName
* @param objectName
* @param stream
* @param size
* @param contextType
* @return
*/
@SneakyThrows
private PutObjectResult putObject(String bucketName, String objectName, InputStream stream, long size,
String contextType) {
byte[] bytes = IOUtils.toByteArray(stream);
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(size);
objectMetadata.setContentType(contextType);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
// 上传
return amazonS3.putObject(bucketName, objectName, byteArrayInputStream, objectMetadata);
}
}
上方基本就做完了,下面是使用阿里云oss进行测试
6. 创建桶测试,不添加完整代码了
配置yml
#阿里云存储设置
oss:
endpoint: XXXX #阿里云域名
access-key: XXXX # 阿里云AK
secret-key: XXXX # 阿里云SK
添加测试方法
/**
* 测试oss
*/
@GetMapping("/testOssProperties")
public AjaxResult loginByPassword() {
ossFileService.createBucket("yizhi-ceshi");
return AjaxResult.success();
}
AjaxResult createBucket(String bucketName);
private final OssTemplate ossTemplate;
@Override
public AjaxResult createBucket(String bucketName) {
ossTemplate.createBucket(bucketName);
return AjaxResult.success();
}
测试结果:阿里云上能看到创建的桶
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rB5B997w-1681906373953)(D:wangCode随记image-20230419195131847.png)]
oginByPassword() {
ossFileService.createBucket(“yizhi-ceshi”);
return AjaxResult.success();
}
```java
AjaxResult createBucket(String bucketName);
private final OssTemplate ossTemplate;
@Override
public AjaxResult createBucket(String bucketName) {
ossTemplate.createBucket(bucketName);
return AjaxResult.success();
}
测试结果:阿里云上能看到创建的桶
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。