Auto Configuration
Dependencies
- Gradle
- Maven
implementation("io.github.danielliu1123:grpc-client-boot-starter")
<dependency>
<groupId>io.github.danielliu1123</groupId>
<artifactId>grpc-client-boot-starter</artifactId>
</dependency>
Usage
Steps to autoconfigure gRPC clients (stubs):
- Specify the clients to be added as Spring Beans.
- Configure request addresses for clients.
Then you can inject the clients using whatever method you prefer.
Specify Stubs
You can configure client classes in two ways.
@EnableGrpcClients
@EnableGrpcClients
can configure packages to scan or directly specify client classes.
Configure packages to scan with basePackages
:
@EnableGrpcClients(basePackages = "io.grpc")
Specify client classes directly with clients
:
@EnableGrpcClients(clients = { SimpleServiceGrpc.SimpleServiceBlockingStub.class })
You can also combine both ways:
@EnableGrpcClients(basePackages = "io.grpc", clients = { SimpleServiceGrpc.SimpleServiceBlockingStub.class })
It's recommended to use clients
to specify client classes directly to avoid adding unnecessary beans into the container,
which can improve startup speed.
Configuration
Similar to @EnableGrpcClients
, you can also specify packages to scan or client classes via configuration files.
grpc:
client:
base-packages: [ io.grpc ]
stubs: [ io.grpc.testing.protobuf.SimpleServiceGrpc.SimpleServiceBlockingStub ]
Configure Request Addresses
You can configure different request addresses (authority) for different client classes, clients configured with the same channel will reuse that channel.
grpc:
client:
channels:
- authority: localhost:9090
stubs: [ io.grpc.*BlockingStub ]
- authority: localhost:9091
stubs: [ io.grpc.*FutureStub ]
There are three ways to configure the clients for a channel:
-
Specify the fully qualified class name of the client using
classes
.grpc:
client:
channels:
- authority: localhost:9090
classes: [ io.grpc.testing.protobuf.SimpleServiceGrpc.SimpleServiceBlockingStub ] -
Use
stubs
to specify client names with Ant-style patterns.grpc:
client:
channels:
- authority: localhost:9090
stubs: [ io.grpc.*BlockingStub ] -
Specify the service name using
services
, e.g.io.grpc.health.v1.HealthGrpc#SERVICE_NAME
.grpc:
client:
channels:
- authority: localhost:9090
services: [ grpc.testing.SimpleService ]
The priority of the configuration methods is classes
> stubs
> services
。
Inject Client
Inject the client using whatever method you prefer, constructor, @Autowired
, setter...
It's just like injecting any other Spring Bean, and respects the Spring Bean lifecycle.
@Component
class MyComponent {
@Autowired
private SimpleServiceGrpc.SimpleServiceBlockingStub stub;
}
Configurations
Configure deadline
for the channel.
grpc:
client:
channels:
- authority: localhost:9090
stubs: [ io.grpc.*BlockingStub ]
deadline: 5000
Full configuration is available in the GrpcClientProperties
.