Reactive Microservices with gRPC and Scala

Functional Ops

(λx.x)eranga
Effectz.AI
2 min readOct 25, 2021

--

Background

In my previous posts I have discussed detailed information about gRPC, Protobuf and gRPC integration with golang based microservices. In this post I’m gonna discuss about integrating gRPC with Scala based microservices. In future post I’m planning to discuss about gRPC and Scala integration with FS2 and ZIO libraries. All the source codes which related to this post available in gitlab. Please clone the repo and continue the post.

Sbt dependency

First I need to add sbt-protoc compiler plugin and ScalaPB Protobuf plugin dependencies to the plugins.sbt file. ScalaPB is a protocol buffer compiler(protoc) plugin for Scala. It will generate Scala case classes, parsers and serializers for your protocol buffers. sbt-protoc plugin used protoc to generate code from Protobuf files. Following is the plugins.sbt file.

Then need to update the build.sbt with gRPC and other dependencies. build.sbt needs to define the instructions to compile Protobuf definitions into Scala codes. It will generates Scala codes from Protobuf file when compiling the project with sbt compile. Following is the build.sbt file.

Protobuf spec

Following is the Protobuf spec file(document.proto) I have used. Create a directory named protobuf inside src/main and add the file document.proto. The gRPC DocumentService contains four main functions. 1) createDocument(unary API), 2) createDocuments(client stream API), 3) getDocuments(server stream API), 4) streamDocuments(bi-directional stream API).

When compiling the project, it will generates the gRPC Scala codes in the target/scala-2.11/src_managed/main/com/rahasak/proto/document/ directory.

gRPC Service

Next I have implemented the gRPC service definitions in the DocumentService. Following is the service implementation in DocumentServiceImpl.scala. It implemented all four gRPC service functions defined in the DocumentService.

gRPC Server

The gRPC server(DocumentServiceApp.scala) registers the services implemented in the DocumentServiceImpl.scala and expose a TCP port to serve the service APIs. In here I have enabled the gRPC server reflection API. The gRPC server reflection can be used by the client to determine the methods and types expose in the gRPC server.

gRPC Client

To consume the functions implemented in the gRPC server I have created the Scala gRPC client(DocumentClientApp.scala). It consumes the four functions implemented in the DocumentServer asynchronously.

Reference

  1. https://scalapb.github.io/docs/grpc/
  2. http://www.beyondthelines.net/computing/grpc-in-scala/
  3. https://blog.knoldus.com/grpc-an-introduction-with-scala-compiler/
  4. https://pbehre.in/posts/grpc-scala-server
  5. https://medium.com/rahasak/microservices-with-golang-and-grpc-f432d0b589b2
  6. https://higherkindness.io/mu-scala/tutorials/grpc-server-client

--

--