一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|編程技術|正則表達式|

服務器之家 - 編程語言 - JAVA教程 - Java負載均衡服務器實現上傳文件同步

Java負載均衡服務器實現上傳文件同步

2020-09-19 23:52賈樹丙 JAVA教程

這篇文章主要介紹了Java負載均衡服務器實現上傳文件同步,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

負載服務器Z,應用服務器A 和B ,從A上傳的附件,如何在B上下載下來?

這個問題我的解決思路如下(后來被一個裝逼的面試官給批評了這種做法,不過我瞧不起他)

服務器A、B 上傳附件的時候,將這個附件備份到服務器Z ,當A、B下載文件的時候,首先會在自己服務器的目錄下尋找,如果找不到,就會從服務器Z 上下載一份到當前服務器。

服務器之間的文件備份通過sftp,參考:http://m.ythuaji.com.cn/article/105390.html(下文中的SftpCustom 類就是這個鏈接里的 “SFTP上傳下載文件例子” 中的類)

這里主要介紹一下重寫上傳、下載的方法時應該添加的代碼

上傳文件,異步操作

?
1
2
3
4
5
6
new Thread(() -> {
 
  SftpCustom fu = new SftpCustom();
  fu.upload(file.getAbsolutePath(), getFileName(fileDescr));
  fu.closeChannel();
}).start();

下載文件,先從當前服務器尋找

?
1
2
3
4
5
6
7
8
9
10
11
12
String tmpPath = roots[0].getPath() + '/' + getFileName(fileDescr);
File file2 = new File(tmpPath);
if (file2.exists()) {
  return FileUtils.openInputStream(file2);
}
 
SftpCustom fu = new SftpCustom();
fu.download(getFileName(fileDescr), tmpPath);
file2 = new File(tmpPath);
inputStream = FileUtils.openInputStream(file2);
fu.closeChannel();
return inputStream;

cuba 框架中重寫上傳文件類FileStorage.java 的代碼如下:

?
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
package com.haulmont.cuba.core.app.custom;
 
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.haulmont.cuba.core.app.FileStorageAPI;
import com.haulmont.cuba.core.app.ServerConfig;
import com.haulmont.cuba.core.entity.FileDescriptor;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.core.sys.AppContext;
import com.haulmont.cuba.core.sys.SecurityContext;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
import static com.haulmont.bali.util.Preconditions.checkNotNullArgument;
 
public class FileStorage implements FileStorageAPI {
 
  private final Logger log = LoggerFactory.getLogger(FileStorage.class);
 
  @Inject
  protected UserSessionSource userSessionSource;
 
  @Inject
  protected TimeSource timeSource;
 
  @Inject
  protected Configuration configuration;
 
  protected boolean isImmutableFileStorage;
 
  protected ExecutorService writeExecutor = Executors.newFixedThreadPool(5,
      new ThreadFactoryBuilder().setNameFormat("FileStorageWriter-%d").build());
 
  protected volatile File[] storageRoots;
 
  @PostConstruct
  public void init() {
    this.isImmutableFileStorage = configuration.getConfig(ServerConfig.class).getImmutableFileStorage();
  }
 
  /**
   * INTERNAL. Don't use in application code.
   */
  public File[] getStorageRoots() {
    if (storageRoots == null) {
      String conf = configuration.getConfig(ServerConfig.class).getFileStorageDir();
      if (StringUtils.isBlank(conf)) {
        String dataDir = configuration.getConfig(GlobalConfig.class).getDataDir();
        File dir = new File(dataDir, "filestorage");
        dir.mkdirs();
        storageRoots = new File[]{dir};
      } else {
        List<File> list = new ArrayList<>();
        for (String str : conf.split(",")) {
          str = str.trim();
          if (!StringUtils.isEmpty(str)) {
            File file = new File(str);
            if (!list.contains(file))
              list.add(file);
          }
        }
        storageRoots = list.toArray(new File[list.size()]);
      }
    }
    return storageRoots;
  }
 
  @Override
  public long saveStream(final FileDescriptor fileDescr, final InputStream inputStream) throws FileStorageException {
    checkFileDescriptor(fileDescr);
 
    File[] roots = getStorageRoots();
 
    // Store to primary storage
 
    checkStorageDefined(roots, fileDescr);
    checkPrimaryStorageAccessible(roots, fileDescr);
 
    File dir = getStorageDir(roots[0], fileDescr);
    dir.mkdirs();
    checkDirectoryExists(dir);
 
    final File file = new File(dir, getFileName(fileDescr));
    checkFileExists(file);
 
    long size = 0;
    OutputStream os = null;
    try {
      os = FileUtils.openOutputStream(file);
      size = IOUtils.copyLarge(inputStream, os);
      os.flush();
      writeLog(file, false);
 
      new Thread(() -> {
        SftpCustom fu = new SftpCustom();
        fu.upload(file.getAbsolutePath(), getFileName(fileDescr));
        fu.closeChannel();
      }).start();
 
    } catch (IOException e) {
      IOUtils.closeQuietly(os);
      FileUtils.deleteQuietly(file);
 
      throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, file.getAbsolutePath(), e);
    } finally {
      IOUtils.closeQuietly(os);
    }
 
    // Copy file to secondary storages asynchronously
 
    final SecurityContext securityContext = AppContext.getSecurityContext();
    for (int i = 1; i < roots.length; i++) {
      if (!roots[i].exists()) {
        log.error("Error saving {} into {} : directory doesn't exist", fileDescr, roots[i]);
        continue;
      }
 
      File copyDir = getStorageDir(roots[i], fileDescr);
      final File fileCopy = new File(copyDir, getFileName(fileDescr));
 
      writeExecutor.submit(new Runnable() {
        @Override
        public void run() {
          try {
            AppContext.setSecurityContext(securityContext);
            FileUtils.copyFile(file, fileCopy, true);
            writeLog(fileCopy, false);
          } catch (Exception e) {
            log.error("Error saving {} into {} : {}", fileDescr, fileCopy.getAbsolutePath(), e.getMessage());
          } finally {
            AppContext.setSecurityContext(null);
          }
        }
      });
    }
 
    return size;
  }
 
  protected void checkFileExists(File file) throws FileStorageException {
    if (file.exists() && isImmutableFileStorage)
      throw new FileStorageException(FileStorageException.Type.FILE_ALREADY_EXISTS, file.getAbsolutePath());
  }
 
  protected void checkDirectoryExists(File dir) throws FileStorageException {
    if (!dir.exists())
      throw new FileStorageException(FileStorageException.Type.STORAGE_INACCESSIBLE, dir.getAbsolutePath());
  }
 
  protected void checkPrimaryStorageAccessible(File[] roots, FileDescriptor fileDescr) throws FileStorageException {
    if (!roots[0].exists()) {
      log.error("Inaccessible primary storage at {}", roots[0]);
      throw new FileStorageException(FileStorageException.Type.STORAGE_INACCESSIBLE, fileDescr.getId().toString());
    }
  }
 
  protected void checkStorageDefined(File[] roots, FileDescriptor fileDescr) throws FileStorageException {
    if (roots.length == 0) {
      log.error("No storage directories defined");
      throw new FileStorageException(FileStorageException.Type.STORAGE_INACCESSIBLE, fileDescr.getId().toString());
    }
  }
 
  @Override
  public void saveFile(final FileDescriptor fileDescr, final byte[] data) throws FileStorageException {
    checkNotNullArgument(data, "File content is null");
    saveStream(fileDescr, new ByteArrayInputStream(data));
  }
 
  protected synchronized void writeLog(File file, boolean remove) {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
 
    StringBuilder sb = new StringBuilder();
    sb.append(df.format(timeSource.currentTimestamp())).append(" ");
    sb.append("[").append(userSessionSource.getUserSession().getUser()).append("] ");
    sb.append(remove ? "REMOVE" : "CREATE").append(" ");
    sb.append("\"").append(file.getAbsolutePath()).append("\"\n");
 
    File rootDir;
    try {
      rootDir = file.getParentFile().getParentFile().getParentFile().getParentFile();
    } catch (NullPointerException e) {
      log.error("Unable to write log: invalid file storage structure", e);
      return;
    }
    File logFile = new File(rootDir, "storage.log");
    try {
      try (FileOutputStream fos = new FileOutputStream(logFile, true)) {
        IOUtils.write(sb.toString(), fos, StandardCharsets.UTF_8.name());
      }
    } catch (IOException e) {
      log.error("Unable to write log", e);
    }
  }
 
  @Override
  public void removeFile(FileDescriptor fileDescr) throws FileStorageException {
    checkFileDescriptor(fileDescr);
 
    File[] roots = getStorageRoots();
    if (roots.length == 0) {
      log.error("No storage directories defined");
      return;
    }
 
    for (File root : roots) {
      File dir = getStorageDir(root, fileDescr);
      File file = new File(dir, getFileName(fileDescr));
      if (file.exists()) {
        if (!file.delete()) {
          throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, "Unable to delete file " + file.getAbsolutePath());
        } else {
          writeLog(file, true);
        }
      }
    }
  }
 
  protected void checkFileDescriptor(FileDescriptor fd) {
    if (fd == null || fd.getCreateDate() == null) {
      throw new IllegalArgumentException("A FileDescriptor instance with populated 'createDate' attribute must be provided");
    }
  }
 
  @Override
  public InputStream openStream(FileDescriptor fileDescr) throws FileStorageException {
    checkFileDescriptor(fileDescr);
 
    File[] roots = getStorageRoots();
    if (roots.length == 0) {
      log.error("No storage directories available");
      throw new FileStorageException(FileStorageException.Type.FILE_NOT_FOUND, fileDescr.getId().toString());
    }
 
    InputStream inputStream = null;
    for (File root : roots) {
      File dir = getStorageDir(root, fileDescr);
 
      File file = new File(dir, getFileName(fileDescr));
      if (!file.exists()) {
        log.error("File " + file + " not found");
        continue;
      }
 
      try {
        inputStream = FileUtils.openInputStream(file);
        break;
      } catch (IOException e) {
        log.error("Error opening input stream for " + file, e);
      }
    }
    if (inputStream != null) {
      return inputStream;
    } else {
      try {
        String tmpPath = roots[0].getPath() + '/' + getFileName(fileDescr);
        File file2 = new File(tmpPath);
        if (file2.exists()) {
          return FileUtils.openInputStream(file2);
        }
 
        SftpCustom fu = new SftpCustom();
        fu.download(getFileName(fileDescr), tmpPath);
        file2 = new File(tmpPath);
        inputStream = FileUtils.openInputStream(file2);
        fu.closeChannel();
        return inputStream;
      } catch (Exception e) {
        throw new FileStorageException(FileStorageException.Type.FILE_NOT_FOUND, fileDescr.getId().toString());
      }
    }
  }
 
  @Override
  public byte[] loadFile(FileDescriptor fileDescr) throws FileStorageException {
    InputStream inputStream = openStream(fileDescr);
    try {
      return IOUtils.toByteArray(inputStream);
    } catch (IOException e) {
      throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fileDescr.getId().toString(), e);
    } finally {
      IOUtils.closeQuietly(inputStream);
    }
  }
 
  @Override
  public boolean fileExists(FileDescriptor fileDescr) {
    checkFileDescriptor(fileDescr);
 
    File[] roots = getStorageRoots();
    for (File root : roots) {
      File dir = getStorageDir(root, fileDescr);
      File file = new File(dir, getFileName(fileDescr));
      if (file.exists()) {
        return true;
      }
    }
    return false;
  }
 
  /**
   * INTERNAL. Don't use in application code.
   */
  public File getStorageDir(File rootDir, FileDescriptor fileDescriptor) {
    checkNotNullArgument(rootDir);
    checkNotNullArgument(fileDescriptor);
 
    Calendar cal = Calendar.getInstance();
    cal.setTime(fileDescriptor.getCreateDate());
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH) + 1;
    int day = cal.get(Calendar.DAY_OF_MONTH);
 
    return new File(rootDir, year + "/"
        + StringUtils.leftPad(String.valueOf(month), 2, '0') + "/"
        + StringUtils.leftPad(String.valueOf(day), 2, '0'));
  }
 
  public static String getFileName(FileDescriptor fileDescriptor) {
    return fileDescriptor.getId().toString() + "." + fileDescriptor.getExtension();
  }
 
  @PreDestroy
  protected void stopWriteExecutor() {
    writeExecutor.shutdown();
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:https://www.cnblogs.com/acm-bingzi/p/nginx-sftp-cuba.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 9自拍视频在线观看 | 99精品国产成人a∨免费看 | 99色在线观看 | 窝窝色资源站 | 成人免费视屏 | 性吟网| jizz女16处| 希岛爱理aⅴ在线中文字幕 午夜综合网 | 九九热综合 | 国产一区二区三区四区波多野结衣 | 美女脱了内裤打开腿让人羞羞软件 | 国产剧情麻豆刘玥视频 | avtt在线 | 亚洲精品高清中文字幕完整版 | 日本不卡高清免费v日本 | 精品亚洲综合在线第一区 | 欧美日韩国产一区二区三区不卡 | 日本妇人成熟免费观看18 | 特级毛片全部免费播放器 | 免费日本在线 | 久久久影院亚洲精品 | 59日本人xxxxxxxxx69 | 免费观看国产视频 | 韩国悲惨事件30无删减在线 | sedog在线长片 | 午夜国产视频 | 国产美女屁股直流白浆视频无遮挡 | 日韩欧美国产在线 | 男人狂躁女人下面的视频免费 | 日本黄a| 91丝袜足控免费网站xx | 国产成人精品免费久久久久 | 成人伊人青草久久综合网破解版 | 毛片在线观看网站 | 日本视频免费看 | 92国产福利视频一区二区 | 秋霞一级成人欧美理论 | 无限资源在线观看高清 | 日本人欧美xx | 国产精品一区二区三 | 窝窝影院午夜色在线视频 |