Getting Started

<- Back to Index

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

Project Setup

Before we start adding the dependencies lets start with some of our recommendation for your project setup.

project setup

We recommend splitting your project into 2-3 separate modules.

  1. The interface project Contains the raw protobuf files and generates the java model and service classes. You probably share this part.
  2. The server project Contains the actual implementation of your project and uses the interface project as dependency.
  3. 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 element is probably all you need to use.

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();
    }

}

Additional Topics


<- Back to Index