当操作完OSS的流后,需要关闭对应的流,否则会造成资源泄漏或者占用服务资源过多。关闭流的方式如下:
```java
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
```
关于OSS连接池的使用,推荐使用Alibaba Cloud SDK for Java中提供 OSSClientBuilder 来构建连接池的连接。在使用OSS服务时,我们一般都需要创建 OSSClient 实例,而 OSSClient 并不是线程安全的,所以需要使用连接池来减少每个线程创建的 OSSClient 实例和连接数。 示例代码如下:
```java
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.Protocol;
import com.aliyun.oss.common.utils.AuthUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public class OSSClientPool {
// 连接池最大连接数
private static int DEFAULT_MAX_CONNECTIONS = 100;
// 默认的空闲时间(单位:毫秒)
private static long DEFAULT_IDLE_TIMEOUT = 5 * 60 * 1000;
// OSS连接池
private BlockingQueue<OSSClient> ossClientPool = new ArrayBlockingQueue<OSSClient>(DEFAULT_MAX_CONNECTIONS);
// OSS连接池中最多使用的连接数
private int maxConnections;
// OSS连接池中空闲连接的超时时间
private long idleTimeout;
// 构造函数
public OSSClientPool() {
this(DEFAULT_MAX_CONNECTIONS, DEFAULT_IDLE_TIMEOUT);
}
public OSSClientPool(int maxConnections, long idleTimeout) {
this.maxConnections = maxConnections;
this.idleTimeout = idleTimeout;
initialize();
}
// 初始化OSS连接池
private void initialize() {
for (int i = 0; i < maxConnections; i++) {
OSSClient ossClient = buildOSSClient();
if (ossClient != null) {
ossClientPool.add(ossClient);
}
}
}
// 构建OSSClient实例
private OSSClient buildOSSClient() {
String endpoint = "yourEndPoint"; // 替换成自己的endpoint
String accessKeyId = "yourAccessKeyId"; // 替换成自己的accessKeyId
String accessKeySecret = "yourAccessKeySecret"; // 替换成自己的accessKeySecret
boolean isCname = false; // 非CNAME模式
OSSClient ossClient = null;
try {
ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ossClient.setEndpoint(endpoint);
ossClient.setCredentials(new DefaultCredentialProvider(accessKeyId, accessKeySecret, null));
ossClient.setProtocol(Protocol.HTTPS);
ossClient.setTimeout(30000);
} catch (Exception e) {
e.printStackTrace();
}
return ossClient;
}
// 获取OSSClient连接
public OSSClient getOSSClient() {
OSSClient ossClient = null;
try {
ossClient = ossClientPool.poll(idleTimeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ossClient == null) {
ossClient = buildOSSClient();
}
return ossClient;
}
// 释放OSSClient连接
public boolean releaseOSSClient(OSSClient ossClient) {
return (ossClientPool.add(ossClient) || ossClientPool.offer(ossClient));
}
// 销毁OSS连接池
public void destroy() {
List<OSSClient> list = new ArrayList<OSSClient>();
ossClientPool.drainTo(list);
for (OSSClient ossClient : list) {
ossClient.shutdown();
}
}
}
```
通过上述的方式,我们可以方便地使用OSS服务进行后端的存储附件。