Search⌘ K
AI Features

Creating and Running a gRPC Server

Explore how to create a robust gRPC server in Java by defining an FTPServer class that manages the server lifecycle. Learn to start the server, add shutdown hooks for graceful termination, and implement methods to block until shutdown, ensuring resource cleanup and connection closure. This lesson equips you with practical skills for managing gRPC server operations and handling concurrency and errors effectively.

In this lesson, we will define the FTPServer class that manages the lifecycle of a gRPC server. It has a server instance that is initialized based on the provided configuration. The class defines methods to start and shut down the server and ensures a graceful shutdown in various scenarios. We will add the following methods to the FTPServer class:

  • start method to start the server, add a shutdown hook for graceful shutdown, and wait for channels to cleanly shutdown.

  • shutDown method (written for testing purposes) to shut down the server.

  • blockUntilShutdown method (written for testing purposes) to block the main thread until the server terminates.

Constructing the FTPServer class

Create a class FTPServer in the io.datajek.ftpservice.server package. This is the same package where we created the FTPService class in the last lesson. The class has two members, a logger and a server object of the ServerServer_class class.

public class FTPServer {
private static final Logger logger = LogManager.getLogger(FTPServer.class.getName());
private final Server server;
}
FTPServer class members

Constructor

The constructor initializes and configures a gRPC server. The constructor of the FTPServer class takes a ServerConfiguration object as a parameter. It can potentially throw IOException and GeneralSecurityException if there are any errors during the server setup.

The ServerConfiguration utility class (created in the Setting up a gRPC Service lesson) manages the server configurationServer_configuration_properties and loads the server properties listed in the ...

public FTPServer(ServerConfiguration serverConfiguration)
throws IOException, GeneralSecurityException {
server = ServerBuilder.forPort(ServerConstants.INSECURE_MODE_PORT)
.addService(new FTPService(serverConfiguration))
.build();
}
FTPServer constructor
...