본문 바로가기

네트워크 통신/grpc

3. spring boot에서 grpc 사용하기

1. server

1) 라이브러리 등록 (pom.xml)

    - dependecy는 grpc를 사용하기 위한 라이브러리들

    - build 부분은 maven으로 proto 파일을 빌드하기 위한 부분

<dependencies>
...
	<!-- For both -->
	<dependency>
    	<groupId>net.devh</groupId>
    	<artifactId>grpc-spring-boot-starter</artifactId>
    	<version>2.5.1.RELEASE</version>
    	<exclusions>
      		<exclusion>
        		<groupId>io.grpc</groupId>
        		<artifactId>grpc-netty-shaded</artifactId>
      		</exclusion>
    	</exclusions>
  	</dependency>
  
	<!-- For the server (only) -->
  	<dependency>
    	<groupId>net.devh</groupId>
	    <artifactId>grpc-client-spring-boot-autoconfigure</artifactId>
    	<version>2.5.1.RELEASE</version>
	    <type>pom</type>
	 </dependency>
</dependencies>

...

<build>
    <extensions>
      <extension>
        <groupId>kr.motd.maven</groupId>
        <artifactId>os-maven-plugin</artifactId>
        <version>1.6.1</version>
      </extension>
    </extensions>
    <plugins>
...
      <plugin>
        <groupId>org.xolstice.maven.plugins</groupId>
        <artifactId>protobuf-maven-plugin</artifactId>
        <version>0.6.1</version>
        <configuration>
          <protocArtifact>
            com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier}
          </protocArtifact>
          <pluginId>grpc-java</pluginId>
          <pluginArtifact>
            io.grpc:protoc-gen-grpc-java:1.4.0:exe:${os.detected.classifier}
          </pluginArtifact>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>compile-custom</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

 

2) proto 파일 생성 

    - 꼭 src/main/proto 폴더에 생성해야 한다. 

    - 다음 스텝에서 proto 파일을 maven으로 빌드할때 maven이 default로 저 폴더에서 proto파일을 찾는다.

syntax = "proto3";
option java_multiple_files = true;
package com.example.grpc_test.proto;

message HelloRequest {
    string firstName = 1;
    string lastName = 2;
}

message HelloResponse {
    string greeting = 1;
}

service HelloService {
    rpc hello(HelloRequest) returns (HelloResponse);
}

 

3) proto 파일 빌드

    - maven clean install

    - target > generated-sources 에 컴파일된 자바 파일이 생성됨

 

4) proto 파일의 service 구현

    - @GrpcService를 붙이면 spring이 grpc 통신을 관리해준다

    - onNext로 response를 보내고, onCompleted로 통신을 종료한다.

@GrpcService
public class HelloServiceImpl extends HelloServiceImplBase {

  @Override
  public void hello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {

    String greeting = new StringBuilder()
        .append("Hello, ")
        .append(request.getFirstName())
        .append(" ")
        .append(request.getLastName())
        .toString();

    System.out.println(greeting);

    HelloResponse response = HelloResponse.newBuilder()
        .setGreeting(greeting)
        .build();

    responseObserver.onNext(response);
    responseObserver.onCompleted();
  }
}

 

-5 ) 서버 포트 설정 (/src/main/resource/application.properties)

server.port=8081
grpc.server.port=9090

 

2. client

1) 라이브러리 등록 (pom.xml)

    - server의 pom.xml과 dependency 일부분만 다르다. (client only 부분)

<dependencies>
...
	<!-- For both -->
	<dependency>
    	<groupId>net.devh</groupId>
    	<artifactId>grpc-spring-boot-starter</artifactId>
    	<version>2.5.1.RELEASE</version>
    	<exclusions>
      		<exclusion>
        		<groupId>io.grpc</groupId>
        		<artifactId>grpc-netty-shaded</artifactId>
      		</exclusion>
    	</exclusions>
  </dependency>
  
    <!-- For the client (only) -->
<dependency>
    <groupId>net.devh</groupId>
    <artifactId>grpc-client-spring-boot-autoconfigure</artifactId>
    <version>2.5.1.RELEASE</version>
    <type>pom</type>
  </dependency>
</dependencies>

...

<build>
    <extensions>
      <extension>
        <groupId>kr.motd.maven</groupId>
        <artifactId>os-maven-plugin</artifactId>
        <version>1.6.1</version>
      </extension>
    </extensions>
    <plugins>
...
      <plugin>
        <groupId>org.xolstice.maven.plugins</groupId>
        <artifactId>protobuf-maven-plugin</artifactId>
        <version>0.6.1</version>
        <configuration>
          <protocArtifact>
            com.google.protobuf:protoc:3.3.0:exe:${os.detected.classifier}
          </protocArtifact>
          <pluginId>grpc-java</pluginId>
          <pluginArtifact>
            io.grpc:protoc-gen-grpc-java:1.4.0:exe:${os.detected.classifier}
          </pluginArtifact>
        </configuration>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>compile-custom</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

 

2) proto 파일 생성 

    - server와 동일

 

3) proto 파일 빌드

  - server와 동일

 

4) server 호출하는 부분 구현

    - 출력 결과 : Hello, Baeldung gRPC

public class CallTest {

  public static void main(String[] args) {
    ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9090)
        .usePlaintext()
        .build();

    HelloServiceGrpc.HelloServiceBlockingStub stub
        = HelloServiceGrpc.newBlockingStub(channel);

    HelloResponse helloResponse = stub.hello(HelloRequest.newBuilder()
        .setFirstName("Baeldung")
        .setLastName("gRPC")
        .build());

    System.out.println(helloResponse.getGreeting());

    channel.shutdown();
  }
}

 

 

 

 

'네트워크 통신 > grpc' 카테고리의 다른 글

4. grpc의 여러가지 통신 기법  (0) 2021.04.25
2. proto3 언어  (0) 2021.04.11
1. grpc 란  (364) 2021.04.04