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@Beanfactory method parameters is experimental. SupportsChannels, and all kinds ofStubs. Use@GrpcClientBeanwhen used in conjunction with@Autowiredor@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@GrpcClientbeans in the Spring context to be used with@Autowiredand@Qualifier. The annotation can be repeatedly added to any of your@Configurationclasses.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 aNameResolverand 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.NameResolverrespectivelyNameResolver.Factory: A class that will be used to resolve the address to a list ofSocketAddresses, 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@GrpcGlobalClientInterceptoror 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 oneCallCredentialsbean is present on your application context then spring will automatically attach it to allStubs (NOTChannels). TheCallCredentialsHelperutility class helps you to create commonly usedCallCredentialstypes and relatedStubTransformer.StubFactory: A factory that can be used to create a specficStubtype from aChannel. MultipleStubFactorys can be registered to support different stub types. See also Configuration -> StubFactory.StubTransformer: A transformer that will be applied to all clientStubs before they are injected. See also Configuration -> StubTransformer.
Accessing the Client
We recommended to inject (@GrpcClient) Stubs instead of plain Channels.
Note: There are different types of
Stubs. 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
@GrpcClientBeans or fields annotated with@GrpcClientthroughout 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