The main function

Everything is ready for the implementation of the main function:

fn main() -> Result<(), Error> {
env_logger::init();
let (tx, rx) = channel();
let addr: SocketAddr = env::var("ADDRESS")?.parse()?;
let mut server = ServerBuilder::new_plain();
server.http.set_addr(addr)?;
let ring = RingImpl::new(tx);
server.add_service(RingServer::new_service_def(ring));
server.http.set_cpu_pool_threads(4);
let _server = server.build()?;

worker_loop(rx)
}

We initialized a logger and created a channel that we will use to send actions from RingImpl to a worker. We extracted SocketAddr from the ADDRESS environment variable and used this value to bind a server to the provided address.

We created a ServerBuilder instance with the new_plain method. It creates a server without TLS, since gRPC supports secure connections and we have to provide a type parameter for ServerBuilder that implements the TlcAcceptor trait. But with new_plain we use the TlasAcceptor stub from the tls_api_stub crate. The ServerBuilder struct contains the http field of the httpbis::ServerBuilder type. We can use this file to set the address to which to bind the server's socket.

After, we create the RingImpl instance and use the add_service method of ServiceBuilder to attach a service implementation, but we have to provide the generic grpc::rt::ServerServiceDefinition definition of the service and we use new_service_def of the RingServer type to create it for the RingImpl instance.

At the end, we set the quantity of threads in the pool that will be used to handle incoming requests and call the build method of ServiceBuilder to start a server. But wait—if you leave the build call method, the main thread will be terminated and you will have to add a loop or other routine to keep the main thread alive.

Luckily, we need a worker and we can use the main thread to run it. If you only need to run the gRPC server, you can use a loop with the thread::park method call, which will block the thread till it is unblocked by the unpark method call. This approach is used internally by asynchronous runtimes.

We will use the worker_loop function call, but we have not implemented this function yet.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.78.102