集成阿里云OSS编写AliyunOSSUtil
文章目录
我们通过调用官方SDK方式集成
阿里云SDK:https://help.aliyun.com/document_detail/32008.htm?spm=a2c4g.11186623.2.6.5032f2eekNXgW7#concept-32008-zh
1、引入sdk依赖
- pom.xml
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
2、添加yml配置文件
- application.yml
oss:
bucket: 你的bucket
endPoint: https://oss-cn-shenzhen.aliyuncs.com
accessKeyId: 你的 accessKeyId
accessKeySecret: 你的 accessKeySecret
3、编写 AliyunOSSUtil文件
3.1 多例模式
package com.mtl.aliyunoss.utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.*;
import java.net.URL;
import java.util.Calendar;
/**
* Aliyun OSS上传工具类
*/
@Component
public class AliyunOSSUtil {
private static String BUCKET_NAME;
private static String KEY_ID;
private static String KEY_SECRET;
private static String END_POINT;
private static final int URL_EXPIRATION = 365 * 10;
@Value("${oss.bucket}")
private String bucketName;
@Value("${oss.endPoint}")
private String accessEndPoint;
@Value("${oss.accessKeyId}")
private String accessKeyId;
@Value("${oss.accessKeySecret}")
private String accessKeySecret;
@PostConstruct
public void init() {
BUCKET_NAME = bucketName;
END_POINT = accessEndPoint;
KEY_ID = accessKeyId;
KEY_SECRET = accessKeySecret;
}
/**
* 打开ossClient
*
* @reutrn ossClient ossClient
*/
private static OSS getOSSClient() {
OSS ossClient = new OSSClientBuilder().build(END_POINT, KEY_ID, KEY_SECRET);
System.out.println(ossClient);
return ossClient;
}
/**
* OSS上传文件-InputStream
*
* @param allPathFile OSS上传的全路径路径+文件名称(/111/1.png)
* @param inputStream 上传的文件流
*/
public static void uploadFile(String allPathFile, InputStream inputStream) {
OSS ossClient = getOSSClient();
try {
ossClient.putObject(BUCKET_NAME, allPathFile, inputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
depoly(ossClient);
}
}
/**
* OSS上传文件-File
*
* @param allPathFile OSS上传的全路径路径+文件名称(/111/1.png)
* @param file 文件
*/
public static void uploadFile(String allPathFile, File file) {
try {
uploadFile(allPathFile, new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* OSS生成文件需要访问的url
*
* @param allPathFile OSS需要生成的文件:路径+文件名称(/111/1.png)
* @reutrn visitUrl 可以访问的url链接
*/
public static String getVisitUrl(String allPathFile) {
OSS ossClient = getOSSClient();
try {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, URL_EXPIRATION);
URL url = ossClient.generatePresignedUrl(BUCKET_NAME, allPathFile, calendar.getTime());
if (url != null) {
return url.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
depoly(ossClient);
}
return null;
}
/**
* 关闭ossClient
*
* @param ossClient ossClient
*/
private static void depoly(OSS ossClient) {
try {
if (ossClient != null) {
ossClient.shutdown();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.2 单例模式
3.2.1 静态内部类-延时加载
- 替换 多例 getOSSClient 方法;
- 加上 SingletonOSS 内部类静态方法
/**
* 内部类静态方法
*/
private static class SingletonOSS {
private final static OSS ossClient = new OSSClientBuilder().build(END_POINT, KEY_ID, KEY_SECRET);
}
/**
* 获取 ossClient
*
* @reutrn OSS OSS访问Client
*/
public static OSS getOSSClient() {
return SingletonOSS.ossClient;
}
3.2.2 枚举-延时加载
- 替换 多例 getOSSClient 方法;
- 加上 SingletonOSS 内部类静态方法
/**
* 使用枚举方法实现单例模式
*/
public enum OSSEnumSignletion { //内部枚举类
INSTANCE;
private OSS ossClient;
/**
* JVM保证这个方法绝对只调用一次
*/
OSSEnumSignletion() {
ossClient = new OSSClientBuilder().build(END_POINT, KEY_ID, KEY_SECRET);
}
public OSS ossClient() {
return ossClient;
}
}
/**
* 获取 ossClient
*
* @reutrn OSS OSS访问Client
*/
public static OSS getOSSClient() {
return OSSEnumSignletion.INSTANCE.ossClient();
}
4、单元测试调用
- 多线程模型并发上传文件
@SpringBootTest
class AliyunossApplicationTests {
@Test
void contextLoads() throws InterruptedException {
long start = System.currentTimeMillis();
int threadNum = 10;
final CountDownLatch countDownLatch = new CountDownLatch(threadNum);
while (threadNum > 0) {
new Thread(() -> {
System.out.println("---------------线程:" + Thread.currentThread());
for (int j = 0; j < 10; j++) {
//上传文件
AliyunOSSUtil.uploadFile("111/1.png", new File("C:\\Users\\mtl\\Desktop\\1.png"));
//获取访问 url
String visitUrl = AliyunOSSUtil.getVisitUrl("111/1.png");
System.out.println(visitUrl);
}
countDownLatch.countDown();
}).start();
threadNum--;
}
//main方法阻塞,直到计数器变为0才会继续执行
countDownLatch.await();
long end = System.currentTimeMillis();
System.out.println("总耗时:" + (end - start) + "ms");
}
}