关于java:springboot文件下载功能开发

38次阅读

共计 2214 个字符,预计需要花费 6 分钟才能阅读完成。

1L 祭天

近期挤到一个需要 基于 docker 集群部署的环境下载各个服务器节点上的日志文件(对应的服务文件门路曾经做了映射)

首先来看一下架构

思路: 所有的服务都有主备之分, 收集日志的思路即是在每个机器节点上装置一个 monitor.jar 的监控服务, 通过以后主程序去调用 monitor 而后返回对应的数据

主程序代码如下


public class LogDownloadController {@GetMapping("loadLOgList")
    public Resp loadLOgList(@RequestParam("remoteIp") String remoteIp,@RequestParam("appName") String appName) {
        List<UploadFile> ja;
        try {String url = String.format("http://%s:%d/api/filelist/files/%s", remoteIp, 8887,appName);
            String res = HttpUtil.get(url, 1000);
            ja = JSONArray.parseObject(res, List.class);
        } catch (Exception e) {ja = Collections.emptyList();
            log.error(e.getMessage());
        }

        return Resp.OK(ja);
    }

    @GetMapping("loadLOgQue")
    public Resp loadLOgQue(@RequestParam("remoteIp") String remoteIp, @RequestParam("appName") String appName, @RequestParam("fileName") String fileName, HttpServletResponse httpServletResponse) {
        try {String url = String.format("http://%s:%d/api/filelist/files/%s/%s", remoteIp, 8887,fileName,appName);
            httpServletResponse.setContentType("application/x-download");
            httpServletResponse.setHeader("content-Disposition", "attachment;filename=" + fileName);
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            HttpUtil.download(url, outputStream,true);
        } catch (Exception e) {log.error(e.getMessage());
        }
        return Resp.OK("success");
    }

}

monitor 服务代码如下:

@RestController
@RequestMapping("api/filelist")
public class FileListController {


    @Autowired
    FileStorageService fileStorageService;

    @GetMapping("/files/{appName}")
    public ResponseEntity<List<UploadFile>> files(@PathVariable("appName") String appName) {List<UploadFile> files = fileStorageService.loadListsByAppName(appName)
                .map(path -> {String fileName = path.getFileName().toString();
                    String url = MvcUriComponentsBuilder
                            .fromMethodName(FileListController.class,
                                    "getFile",
                                    path.getFileName().toString(),appName
                            ).build().toString();
                    return new UploadFile(fileName, url);
                }).collect(Collectors.toList());
        return ResponseEntity.ok(files);
    }

    @GetMapping("/files/{filename:.+}/{appName}")
    public ResponseEntity<Resource> getFile(@PathVariable("filename") String filename,@PathVariable("appName") String appName) {Resource file = fileStorageService.load(filename,appName);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment;filename=\"" + file.getFilename() + "\"")
                .body(file);
    }

}

参考如下
springBoot2.0 基于 restFul 格调的文件下载

正文完
 0