{{announcement.body}}
{{announcement.title}}

Unary Streaming via gRPC

DZone 's Guide to

Unary Streaming via gRPC

In this article, we discuss how to implement Unary Streaming in gRPC in Spring with a simple messaging service.

· Java Zone ·
Free Resource

If you want to get multiple responses and send multiple requests, it is time to use gRPC Streaming concepts. You can't do streaming with REST API, as REST API uses HTTP 1.1. In this blog, I will go through how you can do Unary Streaming via gRPC.

Types of APIs or Streaming in gRPC

gRPC supports four types of APIs to support streaming.

  1. Unary API.
  2. Server API.
  3. Client API.
  4. Bi-directional API.

Types of gRPC streaming

Unary API

Unary RPCs where the client sends a single request to the server and gets a single response back, just like a normal function call.

Java
 




x


1
service GreetService {
2
    // Unary
3
    rpc Greet(GreetRequest) returns (GreetResponse) {};
4
}



GreetService code

When we compile this .proto file, the code will be generated for us and we will have to provide implementations on the client-side and the server-side for the generated API.

Now, we have to set up the server, as shown in the following picture:

Setting up the server

Now, we have to set the medium between server and client.

Setting medium between server and client

Here, 50051 is the port number in which the server is running and usePlaintest() for not providing any type of security.

Now, we have to set up the server and channel. We will provide implementations on the server-side and client-side. You will use stub created from the generated code to call the generated API. Here is the server-side implementation

GreetService implementation

The request to the server is sent through the managed channel using the synchronous stub. An asynchronous stub is used in case of client streaming and bidirectional streaming. Here is the client-side implementation:

Client-side implementation

Finally, you have to up the server by running the server code and send the request from the client. You will get the desired response.

Here is the source code https://github.com/Munandermaan/Streaming-via-grpc.

I will show how to do client, server and bi-directional streaming in my upcoming blogs.

Conclusion

After going through this blog, you will understand how to do Unary Streaming via gRPC in the easiest way.

Reference

https://grpc.io/docs/guides/concepts/.

Topics:
grpc, streaming api

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}