Feign实现微服务间调用返回stream

今天来讲述一下fegin的调用返回stream,得到stream我们可以下载,写入到页面展示图片等;
我们就开始讲述一下:

  • 服务提供者流接口
@RequestMapping(value = "feginProcessDiagram", method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public void genFeginProcessDiagram(HttpServletResponse httpServletResponse, String processId) throws Exception {
    ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
    //流程走完的不显示图
    if (pi == null) {
        return;
    }
    Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
    //使用流程实例ID,查询正在执行的执行对象表,返回流程实例对象
    String InstanceId = task.getProcessInstanceId();
    List < Execution > executions = runtimeService.createExecutionQuery().processInstanceId(InstanceId).list();
    //得到正在执行的Activity的Id
    List < String > activityIds = new ArrayList < > ();
    List < String > flows = new ArrayList < > ();
    for (Execution exe: executions) {
        List < String > ids = runtimeService.getActiveActivityIds(exe.getId());
        activityIds.addAll(ids);
    }
    //获取流程图
    BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
    ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
    ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
    InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds, flows, engconf.getActivityFontName(),
        engconf.getLabelFontName(), engconf.getAnnotationFontName(), engconf.getClassLoader(), 1.0, true);
    OutputStream out = null;
    byte[] buf = new byte[1024];
    int legth = 0;
    try {
        out = httpServletResponse.getOutputStream();
        while ((legth = in .read(buf)) != -1) {
            out.write(buf, 0, legth);
        }
    } finally {
        if ( in != null) {
            in .close();
        }
        if (out != null) {
            out.close();
        }
    }
}
  • 服务提供者远程调用接口
@RequestMapping(value = "/expense/feginProcessDiagram",method = RequestMethod.GET,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
Response genFeginProcessDiagram(@RequestParam("httpServletResponse") HttpServletResponse httpServletResponse, @RequestParam("processId") String processId) throws Exception;

用feign.Response来接收

  • 服务提供者下载文件接口
@RequestMapping(value = "ribbonProcessDiagram/{processId}")
public void genProcessDiagram1(HttpServletResponse httpServletResponse, @PathVariable String processId) throws Exception {
    ResponseEntity<Resource> entity = restTemplate.postForEntity("http://microservice-flowable/expense/ribbonProcessDiagram/{processId}", processId, Resource.class,processId);
    InputStream in = entity.getBody().getInputStream();
    System.out.println(in);

    OutputStream out = null;
    byte[] buf = new byte[1024];
    int legth = 0;
    try {
      out = httpServletResponse.getOutputStream();
      while ((legth = in.read(buf)) != -1) {
        out.write(buf, 0, legth);
      }
    } finally {
      if (in != null) {
        in.close();
      }
      if (out != null) {
        out.close();
      }
    }
}

只要我们拿到InputStream然后我们就可以操作了,下载,写入直接展示图片!

参考:

https://blog.csdn.net/aaronsimon/article/details/82710979

RestTemplate响应中获取输入流InputStream

微服务调用返回文件的问题可以通过使用Feign接口调用来解决。在Feign接口中,可以将文件作为普通参数传递,并将其返回到业务服务中。具体的解决方案如下: 首先,在上下层服务Feign接口中定义文件下载的方法。可以使用`@GetMapping`注解来指定下载文件的路径,并使用`@PathVariable`注解来获取文件名作为参数。同时,使用`consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE`来指定接收的媒体类型为文件。 ```java import feign.Response; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient("prometheus-file") public interface FileFeignClient { @GetMapping(value = "/file/api/v1/files/{file_name}", consumes = MediaType.APPLICATION_OCTET_STREAM_VALUE) Response downFile(@PathVariable("file_name") String fileName); } ``` 然后,在上层服务中将下层服务的文件返回给前端,实现文件下载功能。可以使用`@GetMapping`注解来指定下载文件的路径,并使用`HttpServletResponse`来获取输出。通过Feign接口调用下层服务的方法,获取文件,并将其写入输出中,实现文件下载。 ```java @GetMapping("/file/download") public void downloadProject(HttpServletResponse httpServletResponse) throws IOException { ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream(); Response feignResponse = fileFeignClient.downFile("file_name"); Response.Body feignBody = feignResponse.body(); feignResponse.headers().forEach((String key, Collection<String> value) -> { httpServletResponse.setHeader(key, ((LinkedList<String>) value).get(0)); }); byte\[\] c = new byte\[1024\]; int length; while ((length = feignBody.asInputStream().read(c)) > 0) { servletOutputStream.write(c, 0, length); } servletOutputStream.flush(); servletOutputStream.close(); } ``` 通过以上的解决方案,可以实现微服务调用返回文件的功能。 #### 引用[.reference_title] - *1* [关于微服务传递问题](https://blog.csdn.net/ABestRookie/article/details/122932690)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Spring Boot微服务文件返回实现](https://blog.csdn.net/guyue35/article/details/104481912)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值