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:
startmethod to start the server, add a shutdown hook for graceful shutdown, and wait for channels to cleanly shutdown.shutDownmethod (written for testing purposes) to shut down the server.blockUntilShutdownmethod (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 Server
public class FTPServer {private static final Logger logger = LogManager.getLogger(FTPServer.class.getName());private final Server server;}
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
ServerConfigurationutility class (created in the Setting up a gRPC Service lesson) manages theand loads the server properties listed in the ... server configuration Server_configuration_properties
public FTPServer(ServerConfiguration serverConfiguration)throws IOException, GeneralSecurityException {server = ServerBuilder.forPort(ServerConstants.INSECURE_MODE_PORT).addService(new FTPService(serverConfiguration)).build();}