springboot文件下载功能开发!

1L祭天

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

首先来看一下架构
springboot文件下载功能开发!_第1张图片
思路: 所有的服务都有主备之分,收集日志的思路即是在每个机器节点上安装一个monitor.jar的监控服务,通过当前主程序去调用monitor 然后返回对应的数据

主程序代码如下


public class LogDownloadController {

    @GetMapping("loadLOgList")
    public Resp loadLOgList(@RequestParam("remoteIp") String remoteIp,@RequestParam("appName") String appName) {
        List 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> files(@PathVariable("appName") String appName) {
        List 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 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风格的文件下载

你可能感兴趣的:(springboot文件下载功能开发!)