使用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) 服务注册与发现

posted @   HANFAN  阅读(3062)  评论(8编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示