Spring Boot REST vs gRPC
What's inside this article
⌄
- Spring Boot REST vs gRPC compatibility
- Spring Boot REST doesn’t start
- Spring Boot REST gRPC issue
- Spring Boot REST not working gRPC
Suppose you are using Spring Boot and you have a REST controller HelloRestController.java:
@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:
GrpcServer.java:
@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();
}
}
DataGrpcService.java:
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:
GrpcServer.java:
@Service
public class GrpcServer {
@PostConstruct
public void start(BindableService service) throws Exception {
Server server = ServerBuilder
.forPort(9090)
.addService(new DataGrpcService())
.build();
server.start();
}
}