1. 程式人生 > 實用技巧 >Grpc+MagicOnion的學習和例子

Grpc+MagicOnion的學習和例子

一,什麼是GRPC?

gRPC是一種與語言無關的高效能遠端過程呼叫 (RPC) 框架。

gRPC 的主要優點是:

  • 現代高效能輕量級 RPC 框架。
  • 協定優先 API 開發,預設使用協議緩衝區,允許與語言無關的實現。
  • 可用於多種語言的工具,以生成強型別伺服器和客戶端。
  • 支援客戶端、伺服器和雙向流式處理呼叫。
  • 使用 Protobuf 二進位制序列化減少對網路的使用。

這些優點使 gRPC 適用於:

  • 效率至關重要的輕量級微服務。
  • 需要多種語言用於開發的 Polyglot 系統。
  • 需要處理流式處理請求或響應的點對點實時服務。

微軟介紹地址:https://docs.microsoft.com/zh-cn/aspnet/core/grpc/?view=aspnetcore-3.0

二,我們上程式碼,遠端呼叫的demo,專案結構如下

介面和實現

ServiceInterface

using MagicOnion;
using System;

namespace ServiceInterface
{
    public interface IGrpcTestService : IService<IGrpcTestService>
    {
        UnaryResult<string> SumAsync(int x, int y);
    }
}

GrpcTestService

using MagicOnion;
using
MagicOnion.Server; using ServiceInterface; using System; namespace Service { public class GrpcTestService : ServiceBase<IGrpcTestService>, IGrpcTestService { public async UnaryResult<string> SumAsync(int x, int y) => (x + y).ToString(); } }

服務端

Startup

using System;
using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Loader; using System.Threading.Tasks; using Grpc.Core; using MagicOnion.Server; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Service; namespace grpcDemo { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { #region grpc MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition( ///由於實現不在當前的專案,再新建類庫,所以我們需要手動配置載入的程式集 new[] { AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName("Service")) }, new MagicOnionOptions(true) { MagicOnionLogger = new MagicOnionLogToGrpcLogger() } ); Server server = new Server { Services = { service }, Ports = { new ServerPort("localhost", 6000, ServerCredentials.Insecure) }//預設埠是5000 }; server.Start(); #endregion services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }

GrpcServiceController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Grpc.Core;
using MagicOnion.Client;
using MagicOnion.Server;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ServiceInterface;

namespace grpcDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class GrpcServiceController : ControllerBase
    {
        private readonly ILogger<GrpcServiceController> _logger;

        public GrpcServiceController(ILogger<GrpcServiceController> logger)
        {
            _logger = logger;
        }

        public string Get()
        {
            return "grpc服務端啟動";
        }
    }
}

客戶端 Program

using Grpc.Core;
using MagicOnion.Client;
using ServiceInterface;
using System;

namespace grpcClientDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            // 然後你就可以根據IP和埠拿到對於的服務
            var channel = new Channel("localhost", 6000, ChannelCredentials.Insecure);


            var client = MagicOnionClient.Create<IGrpcTestService>(channel);
            // 呼叫
            var result = client.SumAsync(100, 200).ResponseAsync.Result;

            Console.WriteLine("Client Received:" + result);

            var channel2 = new Channel("localhost", 6000, ChannelCredentials.Insecure);

            var client2 = MagicOnionClient.Create<IGrpcTestService>(channel2);

            var result2 = client2.SumAsync(100, 200).ResponseAsync.Result;

            Console.WriteLine("Client Received:" + result2);
        }
    }
}

啟動服務端後再啟動客戶端,如下圖

這樣簡單的grpc就完成了

PS:如果我們服務端的實現再另一個類庫,我們需要將該類庫的程式集載入進來,要不然會報錯