若依框架—基于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();
}

测试结果:阿里云上能看到创建的桶

在这里插入图片描述

### 回答1: 在Spring Boot中,你可以使用Amazon S3 SDK来将OSS获取的URL存入数据库。 首先,你需要在你的pom.xml文件中添加Amazon S3 SDK依赖: ``` <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-s3</artifactId> <version>1.11.1003</version> </dependency> ``` 然后,在你的代码中使用以下步骤将OSS获取的URL存入数据库: 1. 创建Amazon S3客户端: ``` AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey))) .withRegion(region) .build(); ``` 其中,accessKey和secretKey是你的OSS访问密钥,region是OSS所在的地域信息。 2. 获取文件URL: ``` String url = s3Client.getUrl(bucketName, objectKey).toString(); ``` 其中,bucketName是你的OSS存储桶名称,objectKey是存储对象的唯一标识符。 3. 将URL存入数据库: 你可以使用Spring Data JPA或者MyBatis等ORM框架将URL存入数据库。例如,使用Spring Data JPA: ``` @Entity @Table(name = "file") public class FileEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String url; // getters and setters } ``` ``` @Repository public interface FileRepository extends JpaRepository<FileEntity, Long> { } ``` ``` @Service public class FileService { @Autowired private FileRepository fileRepository; public void saveFile(String name, String url) { FileEntity file = new FileEntity(); file.setName(name); file.setUrl(url); fileRepository.save(file); } } ``` 在保存文件时,调用saveFile方法将文件名和URL存入数据库即可。 注意,以上代码仅供参考,具体实现可能需要根据你的项目需求进行调整。 ### 回答2: 在Spring Boot中将OSS获取的URL存入数据库,可以通过以下步骤实现: 1. 配置阿里云OSS SDK依赖:在项目的pom.xml文件中添加阿里云OSS SDK的依赖,确保能够使用OSS相关的API。 2. 创建数据库表:根据需求,在数据库中创建一个表,用于存储OSS获取的URL。表中可以包含字段如id、url等。 3. 创建实体类:在Java代码中创建与数据库表对应的实体类,例如创建一个OssUrl实体类,包含与表字段对应的属性。 4. 编写处理逻辑:在需要使用OSS获取URL并存入数据库的地方,编写相应的处理逻辑。可以使用OSS SDK提供的API上传文件到OSS,并获取该文件的URL。 5. 将URL存入数据库:获取到URL后,可以使用Spring Data JPA等持久化框架的方法,将URL存入数据库中。 具体实现代码示例如下: ```java // OssUrl 实体类 @Entity public class OssUrl { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String url; // 省略getter和setter方法 } // 服务类 @Service public class OssUrlService { @Autowired private OssUrlRepository ossUrlRepository; @Autowired private OSS ossClient; // 阿里云OSS客户端 public void saveOssUrl(String objectName) { // 上传文件到OSS // 获取文件URL String url = ossClient.generatePresignedUrl(bucketName, objectName, expiration).toString(); // 将URL存入数据库 OssUrl ossUrl = new OssUrl(); ossUrl.setUrl(url); ossUrlRepository.save(ossUrl); } } ``` 需要注意的是,上述示例中的代码仅是一个基本的参考,具体实现还需要根据实际需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yizhi-w

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值