이 글은 기계 번역의 미러 문서이며, 원본 기사로 바로 이동하려면 여기를 클릭해 주세요.

보기: 59053|회답: 9

[.NET 코어] 실전 전투: ASP.NET 코어는 gRPC 통신을 사용합니다

[링크 복사]
게시됨 2019. 11. 11. 오전 10:55:26 | | | |
grpc(하이퍼링크 로그인이 보입니다.)는 구글이 출시한 오픈 소스 고성능 범용 RPC(원격 절차 호출) 프레임워크로, HTTP/2 프로토콜을 사용하고, 다중화를 지원하며, ProtoBuf를 직렬화 도구로 사용하여 언어 간 및 플랫폼 간 지원을 제공합니다.
gRPC는 언어에 구애받지 않는 고성능 원격 프로시저 호출(RPC) 프레임워크입니다.

gRPC의 주요 장점은 다음과 같습니다:

  • 현대적이고 고성능이며 경량화된 RPC 프레임워크입니다.
  • 기본적으로 프로토콜 버퍼를 사용하는 계약 우선 API 개발로, 언어에 구애받지 않는 구현이 가능합니다.
  • 강력한 타입의 서버와 클라이언트를 생성할 수 있는 여러 언어 도구들.
  • 클라이언트, 서버, 양방향 스트리밍 통화를 지원합니다.
  • Protobuf 이진 직렬화로 네트워크 사용을 줄이세요.


이 글은 로 시작합니다. Net Core는 클라이언트 측과 서버 측 통신에 gRPC 프로토콜을 사용합니다.

gRPC 서버 생성

Visual Studio를 실행하고 새 프로젝트 만들기를 선택하세요. 또는 Visual Studio 파일 메뉴에서 새 > 프로젝트를 선택하세요.

새 프로젝트 생성 대화상자에서 gRPC 서비스를 선택한 후 다음을 선택하세요:




다음 그림에서 보듯이 창조가 완료된 후:




gRPC 클라이언트 생성

Visual Studio 두 번째 인스턴스를 열고 새 프로젝트 만들기를 선택하세요.
새 프로젝트 생성 대화상자에서 콘솔 앱(.NET Core)을 선택한 후 다음을 선택하세요.
이름 텍스트 박스에 gRPC-Client를 입력한 후 Create를 선택하세요.


필요한 패키지를 추가하세요

gRPC 클라이언트 프로젝트는 다음 패키지를 요구합니다:
.NET Core 클라이언트를 포함하는 grpc.Net.Client입니다.
Google.Protobuf는 C#용 Protobuf 메시지를 담고 있습니다.
grpc.tools는 Protobuf 파일에 대한 C# 도구 지원을 포함합니다. 툴킷은 런타임에 필요하지 않으므로 의존성은 PrivateAssets="All"으로 표시됩니다.




greet.proto 추가하세요

gRPC 클라이언트 프로젝트에 Protos 폴더를 만들어 보세요.
gRPC Greeter 서비스에서 Protos\greet.proto 파일을 gRPC 클라이언트 프로젝트로 복사하세요.

gRPC-Client.csproj 프로젝트 파일을 편집하고, greet.proto 파일을 참조하는 요소가 포함된 아이템 그룹을 추가하세요 <Protobuf> :





Greeter 클라이언트 생성

gRPC 클라이언트의 Program.cs 파일을 다음 코드로 업데이트하세요:





GrpcChannel을 인스턴스화하여 gRPC 서비스에 연결하는 데 사용되는 정보를 포함하도록 합니다.
GrpcChannel을 사용해 Greeter 클라이언트를 구축하세요.
Greeter 클라이언트는 SayHello 메서드를 호출합니다. SayHello 통화 결과가 표시됩니다.




자신만의 .proto 파일 통신을 만드세요

서브의 Protos 폴더 아래에 다음과 같이 정의된 새로운 userinfo.proto 파일을 생성하세요:


gRPC는 API 개발에 계약 우선 방식을 사용합니다. *.proto 파일에서 서비스와 메시지를 정의하세요.

GrpcService1.csproj 프로젝트 파일을 편집하고, <Protobuf> userinfo.proto 파일을 참조하는 요소가 포함된 항목 그룹을 추가하세요:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>NetcoreApp3.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <protobuf include="protos\greet.proto" grpcServices="Server" />
    <protobuf include="protos\userinfo.proto" grpcServices="Server" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference include="Grpc.AspNetCore" 버전="2.23.1" />
  </ItemGroup>

</Project>


Services 폴더 아래에 새 UserInfoService.cs 파일을 생성하세요. 코드는 다음과 같습니다:

다음 코드로 UserInfoService 서비스를 Startup.cs 등록하세요:

클라이언트를 제외하고, userinfo.proto 파일을 과거에 복사해야 하며, 코드는 다음과 같습니다:

반환 가치:

전 세계 여러분 안녕하세요!
답변: 안녕하세요 itsvse.com
{ "id": "1", "name": "architect", "age": 5, "isVip": true }
{ "id": "2", "name": "itsvse.com", "age": 5 }
처리되지 않은 예외. Grpc.Core.RpcException: Status(StatusCode=취소, 상세="메서드에서 메시지 반환되지 않음.")
   at Grpc.Net.Client.Internal.HttpClientCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method'2 method, String host, CallOptions options, TRequest request)
   Grpc.Core.InterceptingCallInvoker. <BlockingUnaryCall>b__3_0[TRequest,TResponse](TRequest req, ClientInterceptorContext'2 ctx)
   at Grpc.Core.ClientBase.ClientBaseConfiguration.ClientBaseConfigurationInterceptor.BlockingUnaryCall[TRequest,TResponse](TRequest request, ClientInterceptorContext'2 context, BlockingUnaryCallContinuation'2 continuation)
   at grpc.core.Interceptors.InterceptingCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method'2 메서드, String host, CallOptions options, TRequest 요청)
   UserInfo.UserInfoClient.GetUserInfo(GetUserInfoRequest 요청, CallOptions 옵션) in C:\Users\DELL\source\repos\GrpcService1\gRPC-Client\obj\Debug\netcoreapp3.0\ UserinfoGrpc.cs:62행
   at UserInfo.UserInfoClient.GetUserInfo(GetUserInfoRequest request, Metadata 헤더, Nullable'1 deadline, CancellationToken cancellationToken) in C: \Users\DELL\source\repos\GrpcService1\gRPC-Client\obj\Debug\netcoreapp3.0\UserinfoGrpc.cs:line 58
   at gRPC_Client.Program.Main(String[] args) in C:\Users\DELL\source\repos\GrpcService1\gRPC-Client\Program.cs:line 20
계속하려면 어떤 키를 눌러도 부탁드립니다...


반환 값이 null이면 클라이언트가 예외를 던집니다.


바이올린 연주자, 가방 잡아

Fiddler를 사용해 패킷을 캡처하려면, 먼저 클라이언트에서 프록시를 다음과 같이 설정하세요(사실 설정할 수 없고 Fiddler를 직접 열면 됩니다):

서버 측 오류:

fail: Microsoft.AspNetCore.Server.Kestrel[0]
      HTTP/2 over TLS는 HTTP/2 전용 엔드포인트에서 협상되지 않았습니다.
클라이언트 오류:

처리되지 않은 예외. Grpc.Core.RpcException: Status(StatusCode=Internal, Detail="Bad gRPC 응답. 응답 프로토콜이 HTTP/1.1로 강등되었습니다.")
   at Grpc.Net.Client.Internal.HttpClientCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method'2 method, String host, CallOptions options, TRequest request)
   Grpc.Core.InterceptingCallInvoker. <BlockingUnaryCall>b__3_0[TRequest,TResponse](TRequest req, ClientInterceptorContext'2 ctx)
   at Grpc.Core.ClientBase.ClientBaseConfiguration.ClientBaseConfigurationInterceptor.BlockingUnaryCall[TRequest,TResponse](TRequest request, ClientInterceptorContext'2 context, BlockingUnaryCallContinuation'2 continuation)
   at grpc.core.Interceptors.InterceptingCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method'2 메서드, String host, CallOptions options, TRequest 요청)
   UserInfo.UserInfoClient.GetUserInfo(GetUserInfoRequest 요청, CallOptions 옵션) in C:\Users\DELL\source\repos\GrpcService1\gRPC-Client\obj\Debug\netcoreapp3.0\ UserinfoGrpc.cs:62행
   at UserInfo.UserInfoClient.GetUserInfo(GetUserInfoRequest request, Metadata 헤더, Nullable'1 deadline, CancellationToken cancellationToken) in C: \Users\DELL\source\repos\GrpcService1\gRPC-Client\obj\Debug\netcoreapp3.0\UserinfoGrpc.cs:line 58
   at gRPC_Client.Program.Main(String[] args) in C:\Users\DELL\source\repos\GrpcService1\gRPC-Client\Program.cs:line 23
계속하려면 어떤 키를 눌러도 부탁드립니다...


우편 주소: https://localhost:5001/UserInfo/GetUserInfo

내용:

Host: localhost:5001
User-Agent: grpc-dotnet/2.25.0.0
TE: trailers
grpc-accept-encoding: identity,gzip
Content-Type: application/grpc
Content-Length: 7
Fiddler-Encoding: base64


마지막으로 소스 코드를 첨부하세요:

관광객 여러분, 이 게시물의 숨겨진 내용을 보고 싶으시다면 부탁드립니다회답


(끝)




이전의:프로그래머의 정교함: 초보자에서 엔지니어로의 전체 PDF
다음:100개의 무손실 팟 음악
게시됨 2019. 11. 11. 오후 5:46:30 |
ASP.NET 코어는 gRPC 통신을 사용합니다
게시됨 2019. 11. 28. 오후 3:14:53 |
ASP.NET 코어는 gRPC 통신을 사용합니다
게시됨 2019. 11. 28. 오후 3:15:25 |
ASP.NET 코어는 gRPC 통신을 사용합니다
게시됨 2020. 12. 2. 오후 3:52:18 |
이 마지막 실수를 어떻게 해결하셨나요?
게시됨 2020. 12. 7. 오후 8:37:56 |
Grpc.Core 사용;
Microsoft.Extensions.Logging을 사용;
System을 사용;
System.Collections.Generic을 사용;
System.Linq를 사용;
System.Threading.Tasks를 사용;

네임스페이스 GrpcService1
{
    public class UserInfoService : UserInfo.UserInfoBase
    {
        개인 읽기 전용 ILogger<UserInfoService> _logger;
        비공개 정적 목록<UserInfoReply> 사용자정보응답 = 새 목록<UserInfoReply>();
        정적 UserInfoService()
        {
            userInfoReplies.Add(새 UserInfoReply()
            {
                id = 1,
                이름 = "건축가",
                나이 = 5세,
                IsVip = 참
            });
            userInfoReplies.Add(새 UserInfoReply()
            {
                id = 2,
                이름 = "itsvse.com",
                나이 = 5세,
                IsVip = false
            });
            userInfoReplies.Add(새 UserInfoReply()
            {
                id = 3,
                이름 = "작은 쓰레기",
                나이 = 1,
                IsVip = false
            });
        }
        public UserInfoService(ILogger<UserInfoService> logger)
        {
            _logger = 로거;
        }

        public override 작업<UserInfoReply> GetUserInfo(GetUserInfoRequest request, ServerCallContext 컨텍스트)
        {
            Task.Run(() =>
            {
                userInfoReplies.SingleOrDefault(x => x.Id == 요청. Id);
            });
        }
    }
}
게시됨 2020. 12. 7. 오후 9:06:17 |
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter'1.GetResult()
   at Grpc.Net.Client.Internal.HttpClientCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method'2 method, String host, CallOptions options, TRequest request)
   Grpc.Core.InterceptingCallInvoker. <BlockingUnaryCall>b__3_0[TRequest,TResponse](TRequest req, ClientInterceptorContext'2 ctx)
   at Grpc.Core.ClientBase.ClientBaseConfiguration.ClientBaseConfigurationInterceptor.BlockingUnaryCall[TRequest,TResponse](TRequest request, ClientInterceptorContext'2 context, BlockingUnaryCallContinuation'2 continuation)
   at grpc.core.Interceptors.InterceptingCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method'2 메서드, String host, CallOptions options, TRequest 요청)
게시됨 2021. 5. 25. 오전 11:37:34 |
정말 잘 쓰여졌어요, 칭찬하고 칭찬합니다
게시됨 2021. 6. 5. 오전 11:45:21 |
ASP.NET 코어는 gRPC 통신을 사용합니다
 집주인| 게시됨 2025. 8. 13. 오후 3:25:35 |
Postman을 사용해 gRPC 서비스를 테스트(디버깅)
https://www.itsvse.com/thread-11053-1-1.html
면책 조항:
Code Farmer Network에서 발행하는 모든 소프트웨어, 프로그래밍 자료 또는 기사는 학습 및 연구 목적으로만 사용됩니다; 위 내용은 상업적 또는 불법적인 목적으로 사용되지 않으며, 그렇지 않으면 모든 책임이 사용자에게 부담됩니다. 이 사이트의 정보는 인터넷에서 가져온 것이며, 저작권 분쟁은 이 사이트와는 관련이 없습니다. 위 내용은 다운로드 후 24시간 이내에 컴퓨터에서 완전히 삭제해야 합니다. 프로그램이 마음에 드신다면, 진짜 소프트웨어를 지원하고, 등록을 구매하며, 더 나은 진짜 서비스를 받아주세요. 침해가 있을 경우 이메일로 연락해 주시기 바랍니다.

Mail To:help@itsvse.com