使用MagicOnion实现gRPC
1.什么是gRPC
官方文档:https://grpc.io/docs/guides/index.html
2.什么是MagicOnion
MagicOnion开源地址:https://github.com/Cysharp/MagicOnion
3.服务端代码
新建一个WebAPI项目
using MagicOnion;
namespace ServerDefinition
{
// 定义接口和方法,IService,UnaryResult是MagicOnion自带
public interface ITest : IService<ITest>
{
UnaryResult<string> SumAsync(int x, int y);
}
}
using MagicOnion;
using MagicOnion.Server;
using ServerDefinition;
namespace GRPCServer
{
// 实现接口,ServiceBase是MagicOnion自带
public class Test : ServiceBase<ITest>, ITest
{
public async UnaryResult<string> SumAsync(int x, int y) => (x + y).ToString();
}
}
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 System;
namespace GRPCServer
{
public class Startup
{
public Startup(IConfiguration configuration)
{
this.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)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// 通过反射去拿
MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition(new MagicOnionOptions(true)
{
MagicOnionLogger = new MagicOnionLogToGrpcLogger()
});
Server server = new Server
{
Services = { service },
Ports = { new ServerPort(this.Configuration["Service:LocalIPAddress"],//这里是读配置文件 Convert.ToInt32(this.Configuration["Service:Port"]), ServerCredentials.Insecure) }
};
server.Start();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
4.客户端
新建一个控制台程序
using Consul;
using Grpc.Core;
using MagicOnion.Client;
using ServerDefinition;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Client
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// 然后你就可以根据IP和端口拿到对于的服务
var channel = new Channel("192.168.1.8", 8080, ChannelCredentials.Insecure);
var client = MagicOnionClient.Create<ITest>(channel);
// 调用
var result = client.SumAsync(100, 200).ResponseAsync.Result;
Console.WriteLine("Client Received:" + result);
var channel2 = new Channel("192.168.1.8", 8081, ChannelCredentials.Insecure);
var client2 = MagicOnionClient.Create<ITest>(channel2);
var result2 = client2.SumAsync(100, 200).ResponseAsync.Result;
Console.WriteLine("Client Received:" + result2);
}
}
}
5. 思考
GRPC项目创建多个之后,需要一个服务注册和发现的工具。
6.下一篇预告。
使用Consul 实现 MagicOnion(GRpc) 服务注册与发现