Creating and Running a gRPC Server
Write the code for the gRPC server to start the server.
We'll cover the following...
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 config.propertiesfile.
public FTPServer(ServerConfiguration serverConfiguration)throws IOException, GeneralSecurityException {server = ServerBuilder.forPort(ServerConstants.INSECURE_MODE_PORT).addService(new FTPService(serverConfiguration)).build();}
Inside the constructor, a new gRPC server is created by chaining multiple methods, which are briefly explained as under:
.forPort(ServerConstants.INSECURE_MODE_PORT)initializes the ...