Bootstrap

RPC 中 参数传递 ImputStream 流会关闭

实际工作中遇到很多需要对提交的附件处理的场景。那么就涉及到控制层和业务层之间的参数传递。

非RPC,本地方法调用时:

@PostMapping("/import")
    public void import(@RequestParam("file") MultipartFile file) throws IOException{
        return importService.import(file.getInputStream());
    }
@Service
public class ExcelImportServiceImpl implements ExcelImportService {
	 public void import(InputStream inputStream) {
     	//do something
    }
}

这样是完全可以的。

RPC调用(涉及到注册中心,Feign等方式)时:

传递到消费者的流都是被关闭的,导致空指针等异常。

java.lang.NullPointerException: null
	at com.alibaba.excel.ExcelReader.finish(ExcelReader.java:277) ~[easyexcel-2.1.6.jar!/:?]
	at com.alibaba.excel.ExcelReader.finalize(ExcelReader.java:287) [easyexcel-2.1.6.jar!/:?]
	at java.lang.System$2.invokeFinalize(System.java:1270) [?:1.8.0_191]
	at java.lang.ref.Finalizer.runFinalizer(Finalizer.java:102) [?:1.8.0_191]
	at java.lang.ref.Finalizer.access$100(Finalizer.java:34) [?:1.8.0_191]
	at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:217) [?:1.8.0_191]

RPC调用中,可将InputStream转为byte[] 进行参数传递

@PostMapping("/import")
    public void import(@RequestParam("file") MultipartFile file) throws IOException{
        return importService.import(file.getBytes());
    }
@Service
public class ExcelImportServiceImpl implements ExcelImportService {
	 public void import(byte[] bytes) {
	  ByteArrayInputStream inputStream= new ByteArrayInputStream(bytes);
     	//do something
    }
}

InputStream 转 byte []

public static byte[] toByteArray(InputStream input) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024*4];
    int n = 0;
    while (-1 != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
    }
    return output.toByteArray();
}
;