问题
I am looking for a way on how to implement file download functionality using gRPC but I can't find in the documentation how this is done.
What is an optimal way to do this? I wanted to have a gRPC server that holds files and a gRPC client to request something from gRPC.
I have looked at the examples in Java but could not figure out a way on how to do this. I just started reading about gRPC today.
回答1:
You must define a specific message
as data container and you must transfer it to the client in chunks using a stream
.
Example of proto Message and RPC service:
message DataChunk {
bytes data = 1;
}
rpc DownloadProductImage(DownloadProductImageRequest) returns(stream DataChunk){}
In java you can use BufferedInputStream
to stream the resource to the client.
Code example server side.
Code example client side.
回答2:
There are a few possible approaches.
If your file size is small enough, you can define a proto file with a single String field, and dump the entire text content into that field.
If your file size is too large to do this, you might want to chunk the file and use the streaming API to send the file chunk by chunk.
Below is a good guide for getting started with gRPC.
https://grpc.io/docs/tutorials/basic/java.html
回答3:
I have taken the working example from db80 and have created a PR with a full example: https://github.com/grpc/grpc-java/pull/5126
Hopefully they will merge this then everyone can have a working example of this common use-case for GRPC.
来源:https://stackoverflow.com/questions/49312554/grpc-java-file-download-example