1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
| import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
@Slf4j
@Component
public class SftpUtil {
private final SftpConnectionPoolManager connectionPoolManager;
private final SftpProperties sftpProperties;
private final ExecutorService executorService;
// 監控指標
private final Counter uploadCounter;
private final Counter downloadCounter;
private final Counter deleteCounter;
private final Counter errorCounter;
private final Timer uploadTimer;
private final Timer downloadTimer;
public SftpUtil(SftpConnectionPoolManager connectionPoolManager,
SftpProperties sftpProperties,
MeterRegistry meterRegistry) {
this.connectionPoolManager = connectionPoolManager;
this.sftpProperties = sftpProperties;
this.executorService = Executors.newFixedThreadPool(10);
// 初始化監控指標
this.uploadCounter = Counter.builder("sftp.upload.total")
.description("Total number of file uploads")
.register(meterRegistry);
this.downloadCounter = Counter.builder("sftp.download.total")
.description("Total number of file downloads")
.register(meterRegistry);
this.deleteCounter = Counter.builder("sftp.delete.total")
.description("Total number of file deletions")
.register(meterRegistry);
this.errorCounter = Counter.builder("sftp.error.total")
.description("Total number of errors")
.register(meterRegistry);
this.uploadTimer = Timer.builder("sftp.upload.duration")
.description("File upload duration")
.register(meterRegistry);
this.downloadTimer = Timer.builder("sftp.download.duration")
.description("File download duration")
.register(meterRegistry);
}
/**
* 上傳文件
*/
public boolean uploadFile(String localFilePath, String remoteFilePath) {
return uploadTimer.recordCallable(() -> {
boolean success = executeWithRetry(channelSftp -> {
try {
createRemoteDirectoryIfNotExists(channelSftp, getParentPath(remoteFilePath));
try (FileInputStream fis = new FileInputStream(localFilePath)) {
channelSftp.put(fis, remoteFilePath);
log.info("文件上傳成功: {} -> {}", localFilePath, remoteFilePath);
uploadCounter.increment();
return true;
}
} catch (Exception e) {
log.error("文件上傳失敗: {} -> {}", localFilePath, remoteFilePath, e);
errorCounter.increment();
throw new RuntimeException("文件上傳失敗", e);
}
});
return success;
});
}
/**
* 批量上傳文件
*/
public List<CompletableFuture<Boolean>> uploadFilesAsync(List<FileTransferRequest> requests) {
List<CompletableFuture<Boolean>> futures = new ArrayList<>();
for (FileTransferRequest request : requests) {
CompletableFuture<Boolean> future = CompletableFuture.supplyAsync(() ->
uploadFile(request.getLocalPath(), request.getRemotePath()), executorService);
futures.add(future);
}
return futures;
}
/**
* 下載文件
*/
public boolean downloadFile(String remoteFilePath, String localFilePath) {
return downloadTimer.recordCallable(() -> {
boolean success = executeWithRetry(channelSftp -> {
try {
createLocalDirectoryIfNotExists(getParentPath(localFilePath));
try (FileOutputStream fos = new FileOutputStream(localFilePath)) {
channelSftp.get(remoteFilePath, fos);
log.info("文件下載成功: {} -> {}", remoteFilePath, localFilePath);
downloadCounter.increment();
return true;
}
} catch (Exception e) {
log.error("文件下載失敗: {} -> {}", remoteFilePath, localFilePath, e);
errorCounter.increment();
throw new RuntimeException("文件下載失敗", e);
}
});
return success;
});
}
/**
* 下載文件到輸出流
*/
public void downloadFileToStream(String remoteFilePath, OutputStream outputStream) {
executeWithRetry(channelSftp -> {
try {
channelSftp.get(remoteFilePath, outputStream);
log.info("文件下載到流成功: {}", remoteFilePath);
downloadCounter.increment();
return true;
} catch (Exception e) {
log.error("文件下載到流失敗: {}", remoteFilePath, e);
errorCounter.increment();
throw new RuntimeException("文件下載到流失敗", e);
}
});
}
/**
* 獲取文件內容為字符串
*/
public String getFileContent(String remoteFilePath) {
return executeWithRetry(channelSftp -> {
try (InputStream inputStream = channelSftp.get(remoteFilePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
log.info("獲取文件內容成功: {}", remoteFilePath);
return content.toString();
} catch (Exception e) {
log.error("獲取文件內容失敗: {}", remoteFilePath, e);
errorCounter.increment();
throw new RuntimeException("獲取文件內容失敗", e);
}
});
}
/**
* 刪除文件
*/
public boolean deleteFile(String remoteFilePath) {
return executeWithRetry(channelSftp -> {
try {
channelSftp.rm(remoteFilePath);
log.info("文件刪除成功: {}", remoteFilePath);
deleteCounter.increment();
return true;
} catch (Exception e) {
log.error("文件刪除失敗: {}", remoteFilePath, e);
errorCounter.increment();
throw new RuntimeException("文件刪除失敗", e);
}
});
}
/**
* 列出目錄文件
*/
public List<SftpFileInfo> listFiles(String remotePath) {
return executeWithRetry(channelSftp -> {
try {
Vector<ChannelSftp.LsEntry> entries = channelSftp.ls(remotePath);
List<SftpFileInfo> fileInfos = new ArrayList<>();
for (ChannelSftp.LsEntry entry : entries) {
if (!entry.getFilename().equals(".") && !entry.getFilename().equals("..")) {
SftpFileInfo fileInfo = new SftpFileInfo();
fileInfo.setFilename(entry.getFilename());
fileInfo.setSize(entry.getAttrs().getSize());
fileInfo.setModifiedTime(entry.getAttrs().getMTime());
fileInfo.setDirectory(entry.getAttrs().isDir());
fileInfos.add(fileInfo);
}
}
log.info("列出目錄文件成功: {}, 共 {} 個文件", remotePath, fileInfos.size());
return fileInfos;
} catch (Exception e) {
log.error("列出目錄文件失敗: {}", remotePath, e);
errorCounter.increment();
throw new RuntimeException("列出目錄文件失敗", e);
}
});
}
/**
* 檢查文件是否存在
*/
public boolean fileExists(String remoteFilePath) {
return executeWithRetry(channelSftp -> {
try {
channelSftp.stat(remoteFilePath);
return true;
} catch (SftpException e) {
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
return false;
}
throw new RuntimeException("檢查文件存在性失敗", e);
}
});
}
/**
* 創建遠端目錄
*/
public void createRemoteDirectory(String remotePath) {
executeWithRetry(channelSftp -> {
try {
createRemoteDirectoryIfNotExists(channelSftp, remotePath);
log.info("創建遠端目錄成功: {}", remotePath);
return true;
} catch (Exception e) {
log.error("創建遠端目錄失敗: {}", remotePath, e);
errorCounter.increment();
throw new RuntimeException("創建遠端目錄失敗", e);
}
});
}
/**
* 帶重試機制的執行器
*/
private <T> T executeWithRetry(Function<ChannelSftp, T> operation) {
int attempts = 0;
Exception lastException = null;
while (attempts < sftpProperties.getMaxRetries()) {
ChannelSftp channelSftp = null;
try {
channelSftp = connectionPoolManager.borrowConnection();
return operation.apply(channelSftp);
} catch (Exception e) {
lastException = e;
attempts++;
if (channelSftp != null) {
connectionPoolManager.invalidateConnection(channelSftp);
channelSftp = null;
}
if (attempts < sftpProperties.getMaxRetries()) {
log.warn("SFTP 操作失敗,第 {} 次重試", attempts, e);
try {
Thread.sleep(sftpProperties.getRetryDelay());
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("操作被中斷", ie);
}
}
} finally {
if (channelSftp != null) {
connectionPoolManager.returnConnection(channelSftp);
}
}
}
throw new RuntimeException("SFTP 操作失敗,已重試 " + sftpProperties.getMaxRetries() + " 次", lastException);
}
/**
* 創建遠端目錄(如果不存在)
*/
private void createRemoteDirectoryIfNotExists(ChannelSftp channelSftp, String remotePath) throws SftpException {
if (remotePath == null || remotePath.trim().isEmpty()) {
return;
}
String[] dirs = remotePath.split("/");
String currentPath = "";
for (String dir : dirs) {
if (dir.isEmpty()) continue;
currentPath += "/" + dir;
try {
channelSftp.stat(currentPath);
} catch (SftpException e) {
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
channelSftp.mkdir(currentPath);
} else {
throw e;
}
}
}
}
/**
* 創建本地目錄(如果不存在)
*/
private void createLocalDirectoryIfNotExists(String localPath) throws IOException {
if (localPath != null && !localPath.trim().isEmpty()) {
Path path = Paths.get(localPath);
if (!Files.exists(path)) {
Files.createDirectories(path);
}
}
}
/**
* 獲取父路徑
*/
private String getParentPath(String filePath) {
if (filePath == null) return null;
int lastSlashIndex = filePath.lastIndexOf('/');
if (lastSlashIndex > 0) {
return filePath.substring(0, lastSlashIndex);
}
return null;
}
/**
* 獲取連線池狀態
*/
public SftpConnectionPoolStatus getConnectionPoolStatus() {
SftpConnectionPoolStatus status = new SftpConnectionPoolStatus();
status.setActiveConnections(connectionPoolManager.getActiveConnections());
status.setIdleConnections(connectionPoolManager.getIdleConnections());
return status;
}
}
|
留言討論