Getting Started
This section deals with how to get Spring to connect to a grpc server and manage the connection for you.
Table of Contents
Additional Topics
- Getting Started
- Configuration
- Security
- Tests with Grpc-Stubs
Project Setup
Before we start adding the dependencies lets start with some of our recommendation for your project setup.
We recommend splitting your project into 2-3 separate modules.
- The interface project Contains the raw protobuf files and generates the java model and service classes. You probably share this part.
- The server project Contains the actual implementation of your project and uses the interface project as dependency.
- The client projects (optional and possibly many) Any client projects that use the pre-generated stubs to access the server.
Dependencies
Interface-Project
See the server getting started page
Server-Project
See the server getting started page
Client-Project
Maven (Client)
<dependencies>
<dependency>
<groupId>net.devh</groupId>
<artifactId>grpc-client-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>example</groupId>
<artifactId>my-grpc-interface</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Gradle (Client)
apply plugin: 'org.springframework.boot'
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile('net.devh:grpc-client-spring-boot-starter')
compile('my-example:my-grpc-interface')
}
buildscript {
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
Using the Stubs to connect to the Server
This section assumes that you have already defined and generated your Protobuf service.
Explaining the Client Components
The following list contains all features that you might encounter on the client side. If you don’t wish to use any advanced features, then the first two elements are probably all you need to use.
@GrpcClient
: The annotation that marks fields and setters for auto injection of clients. Support for constructor and@Bean
factory method parameters is experimental. SupportsChannel
s, and all kinds ofStub
s. Use@GrpcClientBean
when used in conjunction with@Autowired
or@Inject
.
Note: Services provided by the same application can only be accessed/called in/after theApplicationStartedEvent
. Stubs connecting to services outside of the application can be used earlier; starting with@PostConstruct
/InitializingBean#afterPropertiesSet()
.@GrpcClientBean
: The annotation helps to register@GrpcClient
beans in the Spring context to be used with@Autowired
and@Qualifier
. The annotation can be repeatedly added to any of your@Configuration
classes.Channel
: The Channel is a connection pool for a single address. The target servers might serve multiple grpc-services though. The address will be resolved using aNameResolver
and might point to a fixed or dynamic number of servers.ManagedChannel
: The ManagedChannel is a special variant of a Channel as it allows management operations to the connection pool such as shuting it down.NameResolver
respectivelyNameResolver.Factory
: A class that will be used to resolve the address to a list ofSocketAddress
es, the address will usually be re-resolved when a connection to a previously listed server fails or the channel was idle. See also Configuration -> Choosing the Target.ClientInterceptor
: Intercepts every call before they are handed to theChannel
. Can be used for logging, monitoring, metadata handling, and request/response rewriting. grpc-spring-boot-starter will automatically pick up all client interceptors that are annotated with@GrpcGlobalClientInterceptor
or are manually registered to theGlobalClientInterceptorRegistry
. See also Configuration -> ClientInterceptor.CallCredentials
: A potentially active component that manages the authentication for the calls. It can be used to store credentials or session tokens. It can also be used to authenticate at an authentication provider and then use returned tokens (such as OAuth) to authorize the actual request. In addition to that, it is able to renew the token, if it expired and re-sent the request. If exactly oneCallCredentials
bean is present on your application context then spring will automatically attach it to allStub
s (NOTChannel
s). TheCallCredentialsHelper
utility class helps you to create commonly usedCallCredentials
types and relatedStubTransformer
.StubFactory
: A factory that can be used to create a specficStub
type from aChannel
. MultipleStubFactory
s can be registered to support different stub types. See also Configuration -> StubFactory.StubTransformer
: A transformer that will be applied to all clientStub
s before they are injected. See also Configuration -> StubTransformer.
Accessing the Client
We recommended to inject (@GrpcClient
) Stub
s instead of plain Channel
s.
Note: There are different types of
Stub
s. Not all of them support all request types (streaming calls).
import example.HelloRequest;
import example.MyServiceGrpc.MyServiceBlockingStub;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;
@Service
public class FoobarService {
@GrpcClient("myService")
private MyServiceBlockingStub myServiceStub;
public String receiveGreeting(String name) {
HelloRequest request = HelloRequest.newBuilder()
.setName(name)
.build();
return myServiceStub.sayHello(request).getMessage();
}
}
Also you can feel free to inject stub with @GrpcClientBean
with @Configuration
for more wide usage in
another services.
Note: We recommend using either
@GrpcClientBean
s or fields annotated with@GrpcClient
throughout your application, as mixing the two can cause confusion for future developers.
@Configuration
@GrpcClientBean(
clazz = TestServiceGrpc.TestServiceBlockingStub.class,
beanName = "blockingStub",
client = @GrpcClient("test")
)
public class YourCustomConfiguration {
@Bean
FoobarService foobarService(@Autowired TestServiceGrpc.TestServiceBlockingStub blockingStub) {
return new FoobarService(blockingStub);
}
}
@Service
@AllArgsConstructor
public class FoobarService {
private TestServiceBlockingStub blockingStub;
public String receiveGreeting(String name) {
HelloRequest request = HelloRequest.newBuilder()
.setName(name)
.build();
return blockingStub.sayHello(request).getMessage();
}
}
Additional Topics
- Getting Started
- Configuration
- Security