Spring Boot REST vs gRPC compatibility

Suppose you are using Spring Boot and you have a REST controller:

@RestController
public class HelloRestController {

  @PostMapping
  public String hello(...) {
    ...
  } 
}

At some point you need to connect the gRPC to the project without disabling REST controller. The gRPC code looks something like this:

@Service		
public class GrpcServer {

  @PostConstruct
  public void start(BindableService service) throws Exception {

    Server server = ServerBuilder

        .forPort(9090)

        .addService(new DataGrpcService())

        .build();

    server.start();

    server.awaitTermination();
  }
}
public class DataGrpcService extends DataServiceGrpc.DataServiceImplBase {
	...
}

Then you find out that you can’t start REST server together with gRPC. gRPC will start, but REST will not.

The problem is that gRPC is blocking further code execution. To bypass the blocking, you need to remove awaitTermination() method:

@Service		
public class GrpcServer {

  @PostConstruct
  public void start(BindableService service) throws Exception {

    Server server = ServerBuilder

        .forPort(9090)

        .addService(new DataGrpcService())

        .build();

    server.start();

  }
}

If you still have any questions, feel free to ask me in the comments under this article, or write me on promark33@gmail.com.

If I saved your day, you can support me :)

Leave a Reply

Your email address will not be published.