grpc - console server

2022. 5. 16. 00:00ASPNET/Grpc

반응형

gRPC는 모든 환경에서 실행할 수 있는 최신 오픈 소스 고성능 RPC(원격 프로시저 호출) 프레임워크입니다.

 

gRPC는 처음에 Google에서 만들었습니다. Google은 Stubby 라는 단일 범용 RPC 인프라 를 사용하여 10년 넘게 데이터 센터 내에서 실행되는 수많은 마이크로서비스를 연결했습니다. 2015년 3월, Google은 Stubby의 다음 버전을 빌드하고 오픈 소스로 만들기로 결정했습니다. 그 결과 마이크로서비스에서 컴퓨팅(모바일, 웹, 사물 인터넷)의 "라스트 마일"에 이르는 사용 사례를 강화하기 위해 현재 Google 외부의 많은 조직에서 gRPC가 사용되었습니다.

 

주요 사용 시나리오

  • 마이크로서비스 스타일 아키텍처에서 다국어 서비스를 효율적으로 연결
  • 모바일 장치, 브라우저 클라이언트를 백엔드 서비스에 연결
  • 효율적인 클라이언트 라이브러리 생성

핵심 기능

  • 11개 언어로 된 관용적 클라이언트 라이브러리
  • 유선 및 간단한 서비스 정의 프레임워크로 매우 효율적
  • http/2 기반 전송을 통한 양방향 스트리밍
  • 플러그형 인증, 추적, 로드 밸런싱 및 상태 확인

 

 

 

많은 RPC 시스템과 마찬가지로 gRPC는 매개변수 및 반환 유형을 사용하여 원격으로 호출할 수 있는 메서드를 지정하여 서비스를 정의한다는 아이디어를 기반으로 합니다. 기본적으로 gRPC는 프로토콜 버퍼를 사용합니다.서비스 인터페이스와 페이로드 메시지의 구조를 모두 기술하기 위한 IDL(인터페이스 정의 언어)로 사용됩니다. 원하는 경우 다른 대안을 사용할 수 있습니다.

 

gRPC는 HTTP/2 레이어 위에서 Protocol Buffers를 사용해 직렬화된 바이트 스트림으로 통신하여 JSON 기반의 통신보다 더 가볍고 통신 속도가 빠르다. 때문에 laytency 감소와 더 많은 트래픽을 처리할 수 있는 성능의 이점이 있다.

 

GRPC 에 대한 더 자세한 내용을 알고 싶다면 아래를 참조하자

https://grpc.io/docs/what-is-grpc/introduction/

 

Introduction to gRPC

An introduction to gRPC and protocol buffers.

grpc.io

 

 

 

C# 에서는 ASPNET core 에서 GRPC Service 를 지원하고 있다. 

하지만 여기서는 C# Console 에서 grpc service 를 생성하고 client 를 통해 통신해 보겠다.

 

Create a new project

 

GrpcConsoleServer 생성

Console App project 생성

 

아래와 같이 GrpcConsole 이라는 Project 를 만든다.

 

 

Protos 폴더를 생성

Protos/greet.proto 생성

// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

GrpcConsoleServer.csproj 수정

...
	<ItemGroup>
		<Protobuf Include="Protos\greet.proto" GrpcServices="Server"/>
	</ItemGroup>
...

개발자 명령 프롬프트로 이동

GrpcConsoleServer.csproj 파일이 있는 폴더로 이동 다음 명령을 이용하여 Grpc 관련 package 설치

dotnet add package Google.Protobuf
dotnet add package Grpc
dotnet add package Grpc.Tools

솔루션을 build 한다. 

 

GreeterServer.cs 생성

using Grpc.Core;
using Helloworld;

namespace GrpcConsoleServer;

public class GreeterServer : Greeter.GreeterBase
{
    // Server side handler of the SayHello RPC
    public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
    {
        return Task.FromResult(new HelloReply { Message = "Hello " + request.Name });
    }
}

 

Program.cs

// See https://aka.ms/new-console-template for more information
using Grpc.Core;
using GrpcConsoleServer;
using Helloworld;

const int Port = 30051;
Server server = new Server
{
    Services = { Greeter.BindService(new GreeterServer()) },
    Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
};
server.Start();

Console.WriteLine("Greeter server listening on port " + Port);
Console.WriteLine("Press any key to stop the server...");
Console.ReadKey();

server.ShutdownAsync().Wait();

 

build 후 실행해 보자

 

 

 

관련영상

https://youtu.be/ExqKXLNy9jU

 

반응형

'ASPNET > Grpc' 카테고리의 다른 글

gRPC - Configuration  (0) 2022.05.23
grpc test - grpcui  (0) 2022.05.20
grpc test - grpcurl  (0) 2022.05.19
grpc with aspnet core  (0) 2022.05.18
grpc - console client  (0) 2022.05.17