前几天碰一个故障,图片花的,之前的做法是把图片下载到服务器中再去显示,由此出现此故障,后来一分析,应用集群之后此法会出现严重的问题,故直接改造了,
从FTP中读取数据然后直接显示在页面, 不下载保存到应用服务器中。
/**
* 获取文件集合
* @param request
* @param response
*/
@RequestMapping( params = "method=showPicture")
public void showPicture(HttpServletRequest request, HttpServletResponse response){
String resObjectId = request.getParameter("resObjectId");
String fileName = request.getParameter("fileName");
String ftppicturesavepath = SysConfig.getParamValue("ftp.picture.savepath");
if(ftppicturesavepath.startsWith("/")){
ftppicturesavepath = ftppicturesavepath.replaceFirst("/", "");
}
if(!ftppicturesavepath.endsWith("/")){
ftppicturesavepath = ftppicturesavepath+"/";
}
String picture_ftp_save_path = ftppicturesavepath + resObjectId;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(SysConfig.getParamValue("file.ftp.ip"), Integer.valueOf(SysConfig.getParamValue("file.ftp.port")));
if (!ftpClient.login(SysConfig.getParamValue("file.ftp.username"), SysConfig.getParamValue("file.ftp.password"))) {
throw new BusinessException("ftp连接不上,请检查ftp服务器状态或连接ftp配置");
}
ftpClient.enterLocalPassiveMode();
changWorkingDirectory(picture_ftp_save_path, ftpClient, true);
ftpClient.setControlEncoding("GBK");
FTPFile[] files = ftpClient.listFiles();
FTPFile[] arr$ = files;
int len$ = files.length;
for (int i$ = 0; i$ < len$; ++i$) {
FTPFile file = arr$[i$];
if (fileName.equalsIgnoreCase(file.getName())) {
ServletOutputStream output = null;
InputStream input = ftpClient.retrieveFileStream(file.getName());
output = response.getOutputStream();
response.setContentType("image/jpeg");
byte imageArray[] = new byte[4064];
int len = 0;
while((len = input.read(imageArray)) != -1){
output.write(imageArray, 0, len);
}
input.close();
output.flush();
}
}
}catch (Exception e){
} finally {
if (ftpClient != null) {
try {
ftpClient.disconnect();
} catch (IOException var30) {
}
}
}
}
private void changWorkingDirectory(String remotePath, FTPClient ftpClient, boolean isMakeDir) throws IOException {
if (remotePath != null) {
String[] rps = remotePath.split("/");
for(int i = 0; i < rps.length; ++i) {
if (!ftpClient.changeWorkingDirectory(rps[i])) {
if (!isMakeDir) {
throw new RuntimeException("找不到该目录:" + rps[i]);
}
ftpClient.makeDirectory(rps[i]);
ftpClient.changeWorkingDirectory(rps[i]);
}
}
}
}
处理完故障,分享一把,也当成记录一把吧,后面如果出现此需求,直接上代码。