As we know Tonic uses the Service and Layer mechanism of Tower framework, if we want to add the concurrency limit on the service on the server side, we can do this:
let layer = tower::ServiceBuilder::new().
.load_shed()
.concurrency_limit(2)
.into_inner();
Service::builder()
.layer(layer)
.add_service(greeter)
.add_service(echo)
.serve(addr)
.await?;
The above code we have: the greeter and echo service maximum concurrency is 2, both for the connection of concurrent cap of a total of 4, exert the function of each layer service is the same, I understand it right?
Now what if I want to implement different concurrency limits for the greeter and echo services, say 3 for one and 2 for the other? I couldn't find a corresponding method in Tonic's documentation or code.
However, for the Tower Service it is possible, I can wrap the two services separately, for example:
let greeter = tower::ServiceBuilder::new()
.load_shed()
.concurrency_limit(3)
.service(greeter);
let echo = tower::ServiceBuilder::new()
.load_shed()
.concurrency_limit(2)
.service(echo);
Server::builder()
.add_service(greeter)
.add_service(echo)
.serve(addr)
.await?;
But that won't work. Because add_service() method requires the participation of type must implement the tonic::server::NamedService trait.
I could implement this trait in a newtype, but it only defines a const NAME element.
I'm not very familiar with generic programming in Rust and haven't found a way to implement it yet.
May I ask if anyone understands this or has done similar functions? I need your help, thank you!
You are almost there, the service you are looking for should ideally be generated while compiling. You should have
build.rs:The protofile might look like:
This would generate some code like this:
You would still need to implement the greeter implementation:
You would bring it all together with the server:
With that working, you still face a problem where using different layers may change what you want. You may want to create a wrapper type.
Here is an example that compiles:
Here is the link to compiling code.
Hopefully you should get it working, happy
greeting